关于用Groovy脚本获取JMS属性并打印键值对至日志/文件的问询
Absolutely! You can use log.info() to meet both of your requirements—printing all JMS key-value pairs to logs, and capturing response JMS properties. Let’s walk through practical implementations:
1. Log All JMS Key-Value Pairs with log.info()
First, you’ll need access to your JMS message object (this varies slightly by framework, but the core logic stays the same). Use Groovy to iterate over all JMS properties and log each one:
// Replace 'jmsMessage' with your actual JMS message object reference def jmsPropertyNames = jmsMessage.getPropertyNames() // Iterate through every property and log via log.info() jmsPropertyNames.each { propName -> def propValue = jmsMessage.getProperty(propName) log.info("JMS Property | ${propName}: ${propValue}") }
This will print every JMS property (including your 23 key-value pairs) directly to your application’s log file, provided your logging level is set to INFO or lower.
2. Capture & Log Response JMS Properties
For response messages, the approach is identical—just target the response JMS message instead:
// Replace 'jmsResponseMessage' with your actual response message object def responsePropertyNames = jmsResponseMessage.getPropertyNames() responsePropertyNames.each { propName -> def propValue = jmsResponseMessage.getProperty(propName) log.info("Response JMS Property | ${propName}: ${propValue}") }
3. Optional: Print to an Output File (In Addition to Logs)
If you want to save the key-value pairs to a dedicated file alongside logging, add a file-writing block to the Groovy script:
def outputFilePath = "/path/to/your/jms-properties-output.log" def outputFile = new File(outputFilePath) // Ensure parent directories exist outputFile.parentFile.mkdirs() outputFile.withWriter { writer -> // Log to file AND application logs jmsPropertyNames.each { propName -> def propValue = jmsMessage.getProperty(propName) def logEntry = "JMS Property | ${propName}: ${propValue}" log.info(logEntry) writer.writeLine(logEntry) } }
Quick Notes:
- Double-check that your logging configuration allows
INFOlevel messages to be written to your log file (common configs like Logback or Log4j2 need this enabled). - If you’re working in a specific integration framework (e.g., MuleSoft, Apache Camel), adjust the message object reference to match the framework’s API (but the iteration logic remains unchanged).
内容的提问来源于stack exchange,提问作者Mano Chandran

