I am not sure if it is possible to only create the message in the log file when the message contains certain text? I am using log4j2.xml and below are all my code.
1) The UserService class
package com.example.services;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
#Service
public class UserService {
Logger confirmLogger = LogManager.getLogger("confirmFile");
public void log(){
confirmLogger.warn("printing confirm text with warn");//this should be in the log file
confirmLogger.info("printing confirm text with info");//this should be in the log file
confirmLogger.error("printing confirm text with error");//this should be in the log file
confirmLogger.warn("printing normal text with error");//this should not be inside the log file
}
}
2) the log4j2.xml
I wanted the all.log to contains all the logs while confirm.log will only contains the message that has "confirm" word inside the sentence.
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN">
<Appenders>
<RollingFile name="allFile"
fileName="logs/all.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log"
immediateFlush="true">
<PatternLayout>
<Pattern>%m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB"/>
</Policies>
</RollingFile>
<RollingFile name="confirmFile"
fileName="logs/confirm.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log"
immediateFlush="true">
<PatternLayout>
<ScriptPatternSelector defaultPattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %l - %msg%n">
<Script name="LevelSelector" language="bsh"><![CDATA[
if (logEvent.getMessage().contains("confirm") ) {
return "INFO";
}
return null;
]]>
</Script>
<PatternMatch key="INFO" pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %msg%n"/>
</ScriptPatternSelector>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB"/>
</Policies>
</RollingFile>
<Console name="LogToConsole" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="all">
<AppenderRef ref="LogToConsole" level="ERROR"/>
<AppenderRef ref="confirmFile" level="ALL" />
<AppenderRef ref="allFile" level="ALL" />
</Root>
</Loggers> </Configuration>
Related
I am getting this error:
ERROR asyncRoot contains an invalid element or attribute "immediateFlush"
When I use immediateFlush attribute in appender in log4j2.xml.
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d{dd-MM-yy HH:mm:ss} [$${ctx:instId} - $${ctx:userId}] %c.%M(%L)- %m%n" />
</Console>
<RollingFile name="csroot"
fileName="${cslogs}/cslog.log" filePattern="${cslogs}/$${date:yyyy-MM}/cslog-%d{yyyy-MM-dd}-%i.log">
<PatternLayout pattern="%d{dd-MM-yy HH:mm:ss} [$${ctx:instId} - $${ctx:userId}] %c.%M(%L)- %m%n" immediateFlush="false"/>
<Policies>
<SizeBasedTriggeringPolicy size="100 MB" />
</Policies>
<DefaultRolloverStrategy max="1000">
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
Try with this modification:
<RollingFile name="csroot"
fileName="${cslogs}/cslog.log" filePattern="${cslogs}/$${date:yyyy-MM}/cslog-%d{yyyy-MM-dd}-%i.log" immediateFlush="false">
<PatternLayout pattern="%d{dd-MM-yy HH:mm:ss} [$${ctx:instId} - $${ctx:userId}] %c.%M(%L)- %m%n"/>
<Policies>
<SizeBasedTriggeringPolicy size="100 MB" />
</Policies>
<DefaultRolloverStrategy max="1000">
</DefaultRolloverStrategy>
</RollingFile>
immediateFlush is not an attribute of PatternLayout.
I know its quite an old question but might help somebody.
RollingFile Appender Parameters points out the immediateFlush is the property of the appender. But you have it declared as an attribute for PatternLayout which is what is causing the error.
Sample RollingFile appender configuration:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz"
immediateFlush="false">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="RollingFile"/>
</Root>
</Loggers>
</Configuration>
I'm using the following .xml configuration to log to the console and also to a file.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="basePath">/logs</Property>
</Properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<RollingFile name="File" fileName="${basePath}/log.log" filePattern="${basePath}/log-%d{yyyy-MM-dd}.log" immediateFlush="true">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
The problem is when I use the following code I get logs on the console but nothing is written to a file.
private static final Logger logger = LogManager.getLogger(App.class);
logger.error("Start App");
Also sometimes I get the following messages when I debug:
Note: when I print out System.getProperty("log4j.configurationFile") I get null
I want to configure my log4j.xml with custom level of verbose - say 350 - in order to print up to some verbose level and including new prints of telemetry that will be at this new level - 350.
What is wrong/missing in my file?
<!--print logs of telemetry, warning and above -->
<CustomLevels>
<CustomLevel name="telemetryLevel" intLevel="350"/>
</CustomLevels>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<RollingFile name="deviceTelemetry" fileName="/home/device/telemetry-${date:yyyy-MM-dd}.log" append="false"
filepattern="/home/device/telemetry-${date:yyyy-MM-dd}-%i.log">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10M"/>
</Policies>
<DefaultRolloverStrategy max="5"/>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="deviceTelemetry" level="telemetryLevel">
<AppenderRef ref="deviceTelemetry"/>
</Logger>
<Root>
<AppenderRef ref="Console" level="trace"/>
</Root>
</Loggers>
this way i get the logger in code:
Logger log = LogManager.getLogger("deviceTelemetry");
i don't know yet how to call the logger to append a message. there is a method log(Level level, String message) which gets a level so it might work - i cannot check it yet.
Am little new to web applications, recently I was in need to employ a logging mechanism and for that I choose Log4J2, I went through there guide, and downloaded required libraries. This is what so far I did.
1. Added following jars to web-inf/lib
-- log4j-core2.1.jar
-- log4j-api-2.1.jar
-- log4j-web-2.1.jar
2. Added below xml as, log4j2.xml in java/src directory
<?xml version="1.0" encoding="UTF-8"?>
<configuration name="NONPROD" status="OFF">
<Properties>
<Property name="log-path">logs</Property>
</Properties>
<Appenders>
<Console name="console-log" target="SYSTEM_OUT">
<!-- <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n -->
<!-- </pattern> -->
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<RollingFile name="info-log" fileName="${log-path}/web-info.log"
filePattern="${log-path}/web-info-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="20 MB" />
</Policies>
</RollingFile>
<RollingFile name="error-log" fileName="${log-path}/web-error.log"
filePattern="${log-path}/web-error-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="20 MB" />
</Policies>
</RollingFile>
<RollingFile name="debug-log" fileName="${log-path}/web-debug.log"
filePattern="${log-path}/web-debug-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="20 MB" />
</Policies>
</RollingFile>
<RollingFile name="trace-log" fileName="${log-path}/web-trace.log"
filePattern="${log-path}/web-trace-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="20 MB" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.demo.web.log4j2.file" level="debug"
additivity="false">
<appender-ref ref="trace-log" level="trace" />
<appender-ref ref="error-log" level="error" />
<appender-ref ref="debug-log" level="debug" />
<appender-ref ref="info-log" level="info" />
</Logger>
<Logger name="com.demo.web.log4j2.console" level="all"
additivity="false">
<AppenderRef ref="console-log" />
</Logger>
<Root level="info" additivity="true">
<AppenderRef ref="console-log" />
</Root>
</Loggers>
</configuration>
3. third and last i wrote an small web service to test logging
#Path("/register")
public class Register {
private DataManager mManager;
private static final Logger LOG = LogManager.getLogger(Register.class);
public Register(){
mManager = DataManager.getInstance();
}
#GET
#Path("/{param}")
public Response getMsg(#PathParam("param") String msg) {
LOG.error("Not supported operations");
return Response.status(Response.Status.BAD_REQUEST)
.entity("Not supported").build();
}
But in console, upon trigger get request this is all i got printed.
INFO: Server startup in 35959 ms
Not supported operations // this is not in pattern i supplied in log4j2.xml
// this is my pattern
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
I figure out this is probably due to some thing gone wrong, and am struggling to find the actual cause, being totally new to web programming, please help me out to configure my logger.
Thanks,
Techfist
Your servlet container is using some other logging framework which logs to console. Figure out which logging framework that is and use one of log4j2's bridge libraries to redirect output to your log4j2 setup.
Alright, I found the cause behind this, Issue was primarily happening due to two reasons.
First I was suppose to exclude log4j* pattern from jarsToSkip attribute in catilina property
Second, i had kept two log4j2.xml one inside web-inf other inside java/src, it was supposed to be only present at java/src. two files were not required.
Third, but not mandatory, before deployment just check if log4j2.xml is included inside web-inf/classes or not, if not then simply add it.
that's it, after following this issue was resolved now am getting proper logs.
I'm use to RollingFileAppender on normal log4j. Now I'm switching to log4j2, and cannot get the appender to work.
The File appender below works as expected. But the logging file for RollingFile is never created. Why?
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<File name="FILE" fileName="c:/logs.log">
<PatternLayout pattern="%d %p %c: %m%n" />
</File>
<RollingFile name="ROLLING" fileName="c:/logsroll.log">
<PatternLayout pattern="%d %p %c: %m%n"/>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="0.001 MB"/>
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="FILE" />
<AppenderRef ref="ROLLING" />
</Root>
</Loggers>
</Configuration>
The RollingFile tag is missing a filePattern attribute.
<RollingFile name="ROLLING"
fileName="c:/logsroll.log"
filePattern="c:/logsroll-%i.log">
I used log4j2 version 2.0, in some cases it throws error if you do not set any date in file pattern, in this case you can use some thing like below:
<RollingFile name="MyFile" fileName="d:/log/bsi/admin/total/totalLog.log"
filePattern="d:/log/totalLog-%d{MM-dd-yyyy}-%i.log">
<PatternLayout>
<Pattern>%d %p %c [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="1 MB"/>
</Policies>
<DefaultRolloverStrategy max="2000"/>
</RollingFile>