How to save logs into file with timestamp with log4j2 - java

i have a little problem. I had to change my logging implementation from org.apache.commons.logging to org.apache.logging.log4j. I saved my logs into a "log" directory and each file got a appended timestamp.
I used the following .xml file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="org.springframework.web" level="INFO"/>
<timestamp key="myTimestamp" timeReference="contextBirth" datePattern="yyyy-MM-dd'_'HH-mm-ss"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/logs/app-${myTimestamp}.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd_HH:mm:ss} - %msg%n</Pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>app.%i{yyyy-MM-dd_HH:mm:ss.SSS}}.log</FileNamePattern>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>30MB</MaxFileSize>
</triggeringPolicy>
</appender>
<logger name="com....." level="INFO" additivity="false">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</logger>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Now i wanted to extend my xml file with log4j2, because of some new environments. But i also want to save it in the "logs" directory again. I tried different methods via the documentation and http://www.baeldung.com, but i don't get. My application always writes in the my app.log again without timestamp. How can i realize it? Where is the mistake in my new .xml ?
I thought with this
filePattern="logs/ldapmicroservice.%d{MM-dd-yyyy-HH-mm}.log.gz"
i define the new pattern of my file?
This is my new .xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30"
packages="com......">
<Properties>
<Property name="LOG_PATTERN">
%d{yyyy-MM-dd HH:mm:ss.SSS} %5p %X{mdcData} --- %-40.40c{1.} : %m%n%ex
</Property>
</Properties>
<Appenders>
<RollingFile
name="FILE" fileName="/logs/app.log"
filePattern="logs/app.%d{MM-dd-yyyy-HH-mm}.log.gz"
ignoreExceptions="false">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
</PatternLayout>
<TimeBasedTriggeringPolicy />
</RollingFile>
<Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="${LOG_PATTERN}" />
</Console>
<CloudantAppender name="CloudantAppender"
database="logs"
......
<PatternLayout pattern="${LOG_PATTERN}"/>
</CloudantAppender>
</Appenders>
<Loggers>
<Logger name="com...." level="debug" additivity="false">
<AppenderRef ref="FILE" />
<AppenderRef ref="ConsoleAppender" />
<AppenderRef ref="CloudantAppender" />
</Logger>
<Root level="info">
<AppenderRef ref="FILE" />
<AppenderRef ref="ConsoleAppender" />
<AppenderRef ref="CloudantAppender" />
</Root>
</Loggers>
</Configuration>

I found the solution on my own:
<RollingFile
name="FILE" fileName="/logs/app-${date:yyyy-MM-dd'_'HH-mm-ss}.log"
filePattern="logs/app-%d{yyyy-MM-dd}-%i.log"
ignoreExceptions="false">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd'_'HH-mm-ss} %p %m%n</Pattern>
</PatternLayout>
<TimeBasedTriggeringPolicy />
</RollingFile>

Related

Custom log based on Marker

Anyone knows if it is possible to create log files based on custom Markers using slf4j?
My Log with my custom Marker:
Marker myCustomMarker = MarkerFactory.getMarker("MY_CUSTOM_MARKER");
logger.error(myCustomMarker , "My application log.");
My logback.xml with logs/%marker.log
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
</Pattern>
</layout>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>logs/%marker.log</file>
<append>false</append>
<immediateFlush>true</immediateFlush>
<encoder>
<pattern>%d %p %c{1.} [%t] %m%n</pattern>
</encoder>
</appender>
<logger name="com.mkyong" level="debug" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</logger>
<root level="error">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE" />
</root>
<root level="info">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE" />
</root>
</configuration>
but the result was /logs.log%marker
Thanks for any help

Log4j2: not write into file

I added Log4j2 into my project
implementation 'org.springframework.boot:spring-boot-starter-log4j2'
and added next properties:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n%xwEx"/>
<!-- Крутое, но бесцветное логирование-->
<!-- <PatternLayout pattern="%highlight{%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}.%M():%L - %msg%n}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}"/>-->
</Console>
<RollingFile name="File" fileName="C:/Users/Mi/output.log" filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz" immediateFlush="true">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
<Logger name="org.apache.logging.log4j.filelogger" level="info" additivity="false">
<AppenderRef ref="File"/>
</Logger>
</Loggers>
</Configuration>
App write logs to console, but not in file. As I wait, app shall write logs into file by url C:/Users/Mi/output.log, it creates automatically, I can't delete it while app is wotking, but there no logs. Please advice, what to do.
You are only logging stuff from org.apache.logging.log4j.filelogger package into the "File" appender. The Logger name property is the package/class reference
You should do something like this to get logging to file instead of console:
<Root level="info">
<AppenderRef ref="File"/>
</Root>
If you want console and file do:
<Root level="info">
<AppenderRef ref="File"/>
<AppenderRef ref="Console"/>
</Root>

Own log file for a class, thread java log4j2

There is a class Task. Inherited from Thread.
How do I configure the log4j2 logger to create and write Task-1.log for each thread Task?
My xml:
<?xml version="1.0" encoding="UTF-8"?>
<Properties>
<Property name="pattern">%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n</Property>
</Properties>
<Appenders>
<RollingFile name="fileLogger" fileName="${sys:logFolder}/test.log" filePattern="${sys:logFolder}/test-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>${pattern}</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="${pattern}" />
</Console>
</Appenders>
<Loggers>
<Root level="info" additivity="false">
<appender-ref ref="console" />
<appender-ref ref="fileLogger" />
</Root>
<Logger name="com.test.*" level="info">
<appender-ref ref="fileLogger" level="info" />
</Logger>
</Loggers>

Warnings while running an application

I configured log4j ,and I tested it on an application creating log files for threads but I am getting log4j warnings while it is running and log files are not being created for threads.
log4j:WARN No appenders could be found for logger(com.amazonaws.internal.config.InternalConfig).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN
See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<properties>
<property name="logMsgPattern">%d{HH:mm:ss} %-5level - %msg%n</property>
<property name="logDir">logs</property><!-- ${sys:testLogDir} -->
</properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${logMsgPattern}" />
</Console>
<Routing name="Routing">
<Routes pattern="$${ctx:threadId}">
<Route>
<RollingFile name="RollingFile-${ctx:threadId}"
fileName="${logDir}/${ctx:threadId}.log"
filePattern="${logDir}/%d{yyyy-MM-dd}/${ctx:threadId}-%d{yyyy-MM-dd}.log">
<PatternLayout pattern="${logMsgPattern}" />
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
</Policies>
</RollingFile>
</Route>
</Routes>
</Routing>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console" />
</Root>
<logger name="test" level="INFO" />
<Root level="INFO">
<AppenderRef ref="Console" />
<AppenderRef ref="Routing" />
</Root>
</Loggers>
</Configuration>
I tried with logback instead of log4j and its solved. i can create multiple log files for multiple threads.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<statusListener class="ch.qos.logback.core.status.NopStatusListener" />
<property name="USER_HOME" value="\logs" />
<appender name="FILE-THREAD" class="ch.qos.logback.classic.sift.SiftingAppender">
<!-- This is MDC value -->
<!-- We will assign a value to 'logFileName' via Java code -->
<discriminator>
<key>logFileName</key>
<defaultValue>head0</defaultValue>
</discriminator>
<sift>
<!-- A standard RollingFileAppender, the log file is based on 'logFileName'
at runtime -->
<appender name="FILE-${logFileName}"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${USER_HOME}/${logFileName}.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} %mdc [%thread] %level %logger{35}
- %msg%n
</Pattern>
</encoder>
<rollingPolicy
class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>${USER_HOME}/${logFileName}.%i.log.zip
</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>10</MaxIndex>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
</sift>
</appender>

Log4J send tons of emails for one exception?

I configured Log4J to send me emails when an exception occurs, but when it does, instead of sending me one email, I get A LOT of emails (like 10) for the same exception.
I don't know what's wrong.
Here's my configuration :
<configuration>
<conversionRule conversionWord="coloredLevel" converterClass="play.api.Logger$ColoredLevel" />
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${application.home}/logs/application.log</file>
<encoder>
<pattern>%date - [%level] - from %logger in %thread %n%message%n%xException%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%coloredLevel %logger{15} - %message%n%xException{5}</pattern>
</encoder>
</appender>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>smtp.mandrillapp.com</smtpHost>
<smtpPort>587</smtpPort>
<SSL>true</SSL>
<username>my#email.com</username>
<password>******</password>
<to>me#account.com</to>
<from>support#app.com</from>
<subject>[App error] - %ex{short}</subject>
<cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker">
<bufferSize>5</bufferSize>
</cyclicBufferTracker>
<layout class="ch.qos.logback.classic.html.HTMLLayout">
<pattern>%ex{full}</pattern>
</layout>
<!--<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d%n%throwable{short}%n%n%xEx{full}</pattern>
</layout>-->
</appender>
<logger name="play" level="INFO" />
<logger name="application" level="INFO"/>
<root level="ERROR">
<appender-ref ref="STDOUT" />
<appender-ref ref="EMAIL" />
</root>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration>

Categories