I would like to achieve something like
Logger logger = LoggerFactory.getLogger(MyClassname.class);
logger.info("message1", "message2");
The logs should look like
message1 "some other info coming from log4j2 pattern" message2
Currently I an using pattern Layout to get logs in the desired format but not able to find a way that would help with the given requirement.
edit: Adding a small log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<!-- Logging Properties -->
<Properties>
<Property name="LOG_PATTERN"> %sn | %d{yyyy-MM-dd HH:mm:ss}{GMT+0} | %d{yyyy-MM-dd HH:mm:ss} | %p | %m%n </Property>
<!-- <Property name="APP_LOG_ROOT">/Users/<User_name>/Documents/Logs</Property>-->
</Properties>
<Appenders>
<RollingFile name="debugLog" fileName="app-debug.log"
filePattern="app-debug-%d{yyyy-MM-dd}-%i.log">
<LevelRangeFilter minLevel="ERROR" maxLevel="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<SizeBasedTriggeringPolicy size="10MB" />
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.example" additivity="false" level="debug">
<AppenderRef ref="debugLog" />
</Logger>
</Loggers>
</Configuration>
we want to give each log log line an Id, instead of using %sn we want to create our own id. I am logging to multiple files and %sn uses a static counter shared across all the files.
The logs should look like
line-0 | 2022-03-30 05:00:13 | 2022-03-30 10:30:13| DEBUG | A Sample Debug Message
UPDATE: It seems to be a case for SLF4J MDC (Mapped diagnostic context) (or directly Log4j ThreadContext).
Java code:
MDC.put("ownId", "line-0" /* computeYourOwnIdHere() */);
logger.debug("A Sample Debug Message");
Configuration pattern:
<Property name="LOG_PATTERN"> %X{ownId} | %d{yyyy-MM-dd HH:mm:ss}{GMT+0} | %d{yyyy-MM-dd HH:mm:ss} | %p | %m%n </Property>
previous answer:
logger.info("message1", "message2");
is just an API to build formatted log message. Since the "message1"
does not contain argument placeholder {}
, the "message2"
string is simply discarded. What concrete "other info coming from log4j2 pattern" are you trying to insert into logging message? Your requirement to put it in the middle of message is very unusual, putting aside the question how log analyzing tools would process such a log.
If "some other info coming from log4j2 pattern" message1 message2
would suffice, just use pattern "... %m"
at the end and call log.info("message1 {}","message2")
.