SlideShare a Scribd company logo
Tracing
use cases
Execution time
system status
current environment
parameters
issue
recognition
progress
stackholders
developers
production time
system engineers
managers
users
testers
lawyers DevOps
requirements
easy to use API
stackholder
specific logs
readable logs
completenessperformance
client specific
logging
(UI, console,
build job)
reliable
correctness
use case specific
logging (production,
testing, debugging)
historic data
relevant logs
What to log
• reporter (who discovered)
• affected element
• severity
• message
• issue code
• additional data (e.g. exception object)
Log levels
• built-in: OFF, TRACE, DEBUG, INFO, WARN, ERROR, FATAL
• Custom log levels
• no level inheritance (as in log4j 1.x and logback), because
separation of logger configuration and logger
Log levels (2)
<Configuration … status="INFO">
<Loggers>
<Root level="INFO">
<AppenderRef ref="SYSERROUT" />
</Root>
<Logger name="org.apache.logging.log4j2" level="INFO" />
<Logger name="my.package.MyIgnoreClass" level="OFF" />
</Loggers>
</Configuration>
Appenders
<?xml version="1.0" encoding="UTF-8"?>
<Configuration …>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
…
</Console>
…
</Appenders>
<Loggers>
<Logger name="my.package">
<appender-ref ref="STDOUT" />
</Logger>
</Loggers>
</Configuration>
Appenders
• ConsoleAppender
• FileAppender
– RollingFileAppender
– RandomAccessFileAppender
• Messaging
– JMSAppender
– SMTPAppender
• DB
– JDBCAppender
– JPAAppender
– NoSQLAppender
• Remote
– SocketAppender
– SyslogAppender
Appenders
• Wrapper
– FailoverAppender
– AsyncAppender
<Async name="Async">
<AppenderRef ref="MyFile"/>
</Async>
– RoutingAppender .. explained later with MDC
– RewriteAppender .. explained later with Message API
FailoverAppender
<Failover name="Failover" primary="RollingFile">
<Failovers>
<AppenderRef ref="Console"/>
</Failovers>
</Failover>
Layout
• PatternLayout
• HTMLLayout
• XMLLayout
• JSONLayout
• SerializedLayout
Pattern Layout
<PatternLayout
pattern= " %date{dd.MM.yyyy HH:mm:ss,SSS} %5p %logger
%m%n" />
%5p (oder %level) .. log level, maximal 5 Buchstaben, rechtbündig
%logger .. logger name
%c .. class name
%m .. log message
%n .. platform dependent line break
%M .. class method
Pattern Layout (2)
• %t .. Name of the thread
• xException["none"|"short"|"full"|depth],[filters(packages)}
• xThrowable["none"|"short"|"full"|depth],[filters(packages)}
• xEx{"none"|"short"|"full"|depth],[filters(packages)}
– %xEx{short} .. Nur erste Zeile des Throwable
– %xEx{n} .. n Zeilen
– %xEx{none} oder %xEx{0} .. unterdrücken
• MDC{key}  später erklärt
Properties
<?xml version="1.0" encoding="UTF-8"?>
<Configuration …>
<Properties>
<Property name="defaultDatePattern">
%date{dd.MM.yyyy HH:mm:ss,SSS}
</Property>
<Property name="defaultLoggerPattern">
%5p %logger %marker %m%n
</Property>
<Property name="defaultLogPattern">
${defaultDatePattern} ${defaultLoggerPattern}
</Property>
</Properties>
…
</Configuration>
Nested Diagnostic Context
(NDC)
• stack
• context is stored per thread
• use push and pop to add and remove information
NDC.push("processingLevel2");
log.info("success");
log4j.appender.CA.layout.ConversionPattern
=%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %C %x = %m%n
%x .. Accessing information
Mapped Diagnostic Context
(MDC)
• context is stored per thread
• MDC.put(), MDC.get(), and MDC.remove()
MDC.put("userIP", req.getRemoteAddr());
MDC.put("userName", foo.getName());
log.info("success");
log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd
HH:mm:ss.SSSS} %p %X{userIP} %C %X{userName} = %m%n
%X{userName} .. retrieves value for key "userName"
Routing Appender
<Console name="SYSERR"> … </Console>
<Routing name="ConsoleAppenderRouteIssueCode">
<Routes pattern="${ctx:issueCode}">
<Route>
<Console name="ConsoleAppenderWithIssueCode">
<PatternLayout pattern="${ctx:issueCode} -
${defaultLoggerPattern}"/>
</Console>
</Route>
<Route ref="SYSERR" key="${ctx:issueCode}" />
</Routes>
</Routing>
…
<AppenderRef ref="ConsoleAppenderRoute">
Lookup
●
$${ctx:myThreadContextPropertyKey}
●
${ctx:myThreadMapContextPropertyKey}
●
${sys:mySystemPropertyKey}
●
${map:myMapMessageKey}
●
$${date:MM-dd-yyyy}
●
$${env:USER}
●
${java:runtime}
●
$${jndi:logging/context-name}
●
define custom lookup plugins
Markers
private static final Marker SQL_MARKER =
MarkerManager.getMarker("SQL");
private static final Marker UPDATE_MARKER =
MarkerManager.getMarker("SQL_UPDATE", SQL_MARKER);
private static final Marker QUERY_MARKER =
MarkerManager.getMarker("SQL_QUERY", SQL_MARKER);
…
logger.debug(QUERY_MARKER, "SELECT * FROM {}", table);
Filters
BurstFilter .. throttle logging when too many logs produced
ThresholdFilter .. filters by log level ranges
RegexFilter .. messages have to match regex
MarkerFilter .. log event filter by marker resp. its sub type
TimeFilter .. log only at certain times of day
MapFilter .. filters by entries in MapMessage
StructuredDataFilter .. special MapFilter
DynamicThresholdFilter .. z.B. debug only for user id X
ThreadContextMapFilter .. ThreadContext Map entries
CompositeFilter .. apply multiple filters
Regex Filter
<?xml version="1.0" encoding="ASCII"?>
<Configuration name=„MyLogger" …>
…
<Filters>
<RegexFilter regex=".*stringToMatch.*" onMatch="DENY"
onMismatch="NEUTRAL"/>
</Filters>
…
</Configuration>
Thread Context Map Filter
<Loggers>
…
<Root level="error">
<AppenderRef ref="RollingFile"/>
<ThreadContextMapFilter onMatch="ACCEPT"
onMismatch="NEUTRAL" operator="or">
<KeyValuePair key="foo" value="bar"/>
<KeyValuePair key="User2" value="WARN"/>
</ThreadContextMapFilter>
</Root>
</Loggers>
Message API
• pass built-in or custom message objects
• org.apache.logging.log4j.message
– ParameterizedMessage
– MapMessage
– SimpleMessage
– ObjectMessage
– Message
logger.info(new LoggedInMessage(map, user));
Rewrite
Logger logger = LogManager.getLogger(MyClass.class);
Map<String, String> msg = new HashMap<String, String>();
msg.put("creditcard", "123456789");
logger.info(new MapMessage(msg));
Rewrite (2)
<Rewrite name="rewrite">
<AppenderRef ref="myweb"/>
<MapRewritePolicy mode="Update">
<KeyValuePair key="creditcard" value="XXXXXXXXXX"/>
</MapRewritePolicy>
</Rewrite>
<Logger …>
<Appender-Ref ref="rewrite" />
</Logger>
source: https://gomtiprabha.wordpress.com/2014/03/11/rewrite-appender-in-log4j2/
Flow tracing
public String method(String input) {
logger.entry(input);
…
return logger.exit();
}
package my.custom.log4j2.plugins;
@Plugin(name = "Sandbox", type = "Core", elementType = "appender")
public class SandboxAppender extends AppenderBase {
private SandboxAppender(String name, Filter filter) {
super(name, filter, null);
}
public void append(LogEvent event) {
System.out.println(event.getMessage().getFormattedMessage());
}
@PluginFactory
public static SandboxAppender createAppender(
@PluginAttr("name") String name,
@PluginElement("filters") Filter filter) {
return new SandboxAppender(name, filter);
}
}
Plug-in infrastructure
Plug-in infrastructure (2)
<configuration … packages="my.custom.log4j2.plugins">
…
<appenders>
<Sandbox />
</appender>
…
</configuration>
Reconfigure
<?xml version="1.0" encoding="UTF-8"?>
<configuration monitorInterval="30">
...
</configuration>
• monitoring interval is a value in seconds
• log4j 2 would reconfigure logging in case something has
changed in your configuration
• log4j 2.0 does not lose logging events at the time of
reconfiguration
XInclude
<?xml version="1.0" encoding="UTF-8"?>
<configuration …>
<ThresholdFilter level="debug"/>
<xi:include href="log4j-xinclude-appenders.xml" />
<xi:include href="log4j-xinclude-loggers.xml" />
</configuration>
Performance
source: https://logging.apache.org/log4j/2.x/manual/async.html
Logger configuration
• Centralize
• different context selectors
– ThreadLocal
– Classloader
– JNDI
– AsyncLogger
• Make all loggers async
– Bundle
OSGi
• Configure BundleContextSelector
– associates LoggerContexts with the ClassLoader of the
bundle that created the caller of the getLogger call
• Own logger API and central logger config
– Derive Eclipse plug-in project from log4j2 jars
– Define fragment project to define your own logger API
• In MANIFEST set
– Eclipse-ExtensibleAPI: true
Programmatic access
-Dlog4j.configurationFile= ...
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig =
config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
loggerConfig.setLevel(level);
ctx.updateLoggers(); // loggers refetch information from their
LoggerConfig
Bad practice
• logging errors that has been already handled by application
code (e.g. failed login)
• log messages with line breaks
• non unified formatted log messages (no tabs)
• long log messages (can be avoid by shorten the package
name)
• in tests use logging where assertions would have been a
better choice (as they really enforce expected behavior
where logs can be ignored)
• not logging exception objects
• using custom appenders holding state
System.out.println(...)
System.err.println(...)
exception.printStackTrace()
FileWriter writer = ...;
writer.write(...);
writer.close();
LOGGER.error(...)
Bad practice (2)
Bad practice (3)
• use timestamps for every event
• log thread name
• log source of event (e.g. class name and message)
• log ids from domain (e.g. transaction id)
• concise and descriptive messages
• use rolling file appender (to restrict single log file size)
• log method inputs and output at debug resp. trace level
• log full exception objects
• log no more than necessary in production
Good practice
Good practice (2)
Log4J2 + Xtend Active
Annotations
@Delegate (built-in)
to derive custom loggers with a few
customized methods
@Log
to initialize instance log field with correct
class as parameter
@Traceable
To annotate methods, so that logger.entry
and logger.exit with input and output
parameters are generated
Links
• Log4j2
• Apache Log4j 2.0 - Worth the Upgrade?
• The new log4j 2.0
• The Logging Olympics – A Race Between Today’s Top 5 Java
Logging Frameworks

More Related Content

What's hot

Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
Thibaud Desodt
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
priya_trivedi
 
core java
core javacore java
core java
Roushan Sinha
 
Socket.IO
Socket.IOSocket.IO
Socket.IO
Davide Pedranz
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
Sandeep Rawat
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
mahir jain
 
Python Virtual Environment.pptx
Python Virtual Environment.pptxPython Virtual Environment.pptx
Python Virtual Environment.pptx
Abdullah al Mamun
 
Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".
SudhanshuVijay3
 
Sap erp sp ehp基本 システム更新への基礎知識
Sap erp sp ehp基本 システム更新への基礎知識Sap erp sp ehp基本 システム更新への基礎知識
Sap erp sp ehp基本 システム更新への基礎知識
Shiroh Kinoshita
 
Getting Started with Spring Authorization Server
Getting Started with Spring Authorization ServerGetting Started with Spring Authorization Server
Getting Started with Spring Authorization Server
VMware Tanzu
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
Phat VU
 
Java Logging
Java LoggingJava Logging
Java Logging
Zeeshan Bilal
 
TypeScript
TypeScriptTypeScript
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
NestJS
NestJSNestJS
NestJS
Wilson Su
 
Explain it to Me Like I’m 5: Oauth2 and OpenID
Explain it to Me Like I’m 5: Oauth2 and OpenIDExplain it to Me Like I’m 5: Oauth2 and OpenID
Explain it to Me Like I’m 5: Oauth2 and OpenID
VMware Tanzu
 
Spring boot
Spring bootSpring boot
Spring boot
Pradeep Shanmugam
 
Spring Boot
Spring BootSpring Boot
Spring Boot
koppenolski
 
Learning Greenplum Distributed Transaction
Learning Greenplum Distributed TransactionLearning Greenplum Distributed Transaction
Learning Greenplum Distributed Transaction
Chen Wang
 

What's hot (20)

Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
core java
core javacore java
core java
 
Socket.IO
Socket.IOSocket.IO
Socket.IO
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Python Virtual Environment.pptx
Python Virtual Environment.pptxPython Virtual Environment.pptx
Python Virtual Environment.pptx
 
Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".
 
Sap erp sp ehp基本 システム更新への基礎知識
Sap erp sp ehp基本 システム更新への基礎知識Sap erp sp ehp基本 システム更新への基礎知識
Sap erp sp ehp基本 システム更新への基礎知識
 
Getting Started with Spring Authorization Server
Getting Started with Spring Authorization ServerGetting Started with Spring Authorization Server
Getting Started with Spring Authorization Server
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
Java Logging
Java LoggingJava Logging
Java Logging
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Interface in java
Interface in javaInterface in java
Interface in java
 
NestJS
NestJSNestJS
NestJS
 
Explain it to Me Like I’m 5: Oauth2 and OpenID
Explain it to Me Like I’m 5: Oauth2 and OpenIDExplain it to Me Like I’m 5: Oauth2 and OpenID
Explain it to Me Like I’m 5: Oauth2 and OpenID
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Learning Greenplum Distributed Transaction
Learning Greenplum Distributed TransactionLearning Greenplum Distributed Transaction
Learning Greenplum Distributed Transaction
 

Viewers also liked

Mongo DB schema design patterns
Mongo DB schema design patternsMongo DB schema design patterns
Mongo DB schema design patterns
joergreichert
 
OkLab Leipzig (state: 2017)
OkLab Leipzig (state: 2017)OkLab Leipzig (state: 2017)
OkLab Leipzig (state: 2017)
joergreichert
 
Modell-getriebene Softwareentwicklung für Lego Mindstorms NXT
Modell-getriebene Softwareentwicklung für Lego Mindstorms NXTModell-getriebene Softwareentwicklung für Lego Mindstorms NXT
Modell-getriebene Softwareentwicklung für Lego Mindstorms NXT
joergreichert
 
Using openArchitectureWare 4.0 in domain "registration"
Using openArchitectureWare 4.0 in domain "registration"Using openArchitectureWare 4.0 in domain "registration"
Using openArchitectureWare 4.0 in domain "registration"
joergreichert
 
Using JIRA and Confluence to support ITIL like processes
Using JIRA and Confluence to support ITIL like processesUsing JIRA and Confluence to support ITIL like processes
Using JIRA and Confluence to support ITIL like processes
joergreichert
 
P3 - Building a corporate update site
P3 - Building a corporate update site P3 - Building a corporate update site
P3 - Building a corporate update site
joergreichert
 
MOOCs
MOOCsMOOCs
Advanced language testing with XPECT
Advanced language testing with XPECTAdvanced language testing with XPECT
Advanced language testing with XPECT
joergreichert
 
Map technologies
Map technologiesMap technologies
Map technologies
joergreichert
 
Spray Democamp Dresden 2011-11-08
Spray Democamp Dresden 2011-11-08Spray Democamp Dresden 2011-11-08
Spray Democamp Dresden 2011-11-08
joergreichert
 

Viewers also liked (10)

Mongo DB schema design patterns
Mongo DB schema design patternsMongo DB schema design patterns
Mongo DB schema design patterns
 
OkLab Leipzig (state: 2017)
OkLab Leipzig (state: 2017)OkLab Leipzig (state: 2017)
OkLab Leipzig (state: 2017)
 
Modell-getriebene Softwareentwicklung für Lego Mindstorms NXT
Modell-getriebene Softwareentwicklung für Lego Mindstorms NXTModell-getriebene Softwareentwicklung für Lego Mindstorms NXT
Modell-getriebene Softwareentwicklung für Lego Mindstorms NXT
 
Using openArchitectureWare 4.0 in domain "registration"
Using openArchitectureWare 4.0 in domain "registration"Using openArchitectureWare 4.0 in domain "registration"
Using openArchitectureWare 4.0 in domain "registration"
 
Using JIRA and Confluence to support ITIL like processes
Using JIRA and Confluence to support ITIL like processesUsing JIRA and Confluence to support ITIL like processes
Using JIRA and Confluence to support ITIL like processes
 
P3 - Building a corporate update site
P3 - Building a corporate update site P3 - Building a corporate update site
P3 - Building a corporate update site
 
MOOCs
MOOCsMOOCs
MOOCs
 
Advanced language testing with XPECT
Advanced language testing with XPECTAdvanced language testing with XPECT
Advanced language testing with XPECT
 
Map technologies
Map technologiesMap technologies
Map technologies
 
Spray Democamp Dresden 2011-11-08
Spray Democamp Dresden 2011-11-08Spray Democamp Dresden 2011-11-08
Spray Democamp Dresden 2011-11-08
 

Similar to Log4j2

Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in Scala
Knoldus Inc.
 
Logstash
LogstashLogstash
Logstash
Rajgourav Jain
 
Logging for Production Systems in The Container Era
Logging for Production Systems in The Container EraLogging for Production Systems in The Container Era
Logging for Production Systems in The Container Era
Sadayuki Furuhashi
 
Docker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic StackDocker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic Stack
Jakub Hajek
 
Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek
PROIDEA
 
Why you should be using structured logs
Why you should be using structured logsWhy you should be using structured logs
Why you should be using structured logs
Stefan Krawczyk
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...
Joris Kuipers
 
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Red Hat Developers
 
Play Framework Logging
Play Framework LoggingPlay Framework Logging
Play Framework Logging
mitesh_sharma
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
Bartosz Konieczny
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
Positive Hack Days
 
11i Logs
11i Logs11i Logs
TO Hack an ASP .NET website?
TO Hack an ASP .NET website?  TO Hack an ASP .NET website?
TO Hack an ASP .NET website?
Positive Hack Days
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guide
Ady Liu
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
Jennifer Bourey
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation
Biju Thomas
 
Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in Scala
Knoldus Inc.
 
Kommons
KommonsKommons
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
Mustafa TURAN
 

Similar to Log4j2 (20)

Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in Scala
 
Logstash
LogstashLogstash
Logstash
 
Logging for Production Systems in The Container Era
Logging for Production Systems in The Container EraLogging for Production Systems in The Container Era
Logging for Production Systems in The Container Era
 
Docker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic StackDocker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic Stack
 
Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek
 
Why you should be using structured logs
Why you should be using structured logsWhy you should be using structured logs
Why you should be using structured logs
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
 
I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...
 
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
 
Play Framework Logging
Play Framework LoggingPlay Framework Logging
Play Framework Logging
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
11i Logs
11i Logs11i Logs
11i Logs
 
TO Hack an ASP .NET website?
TO Hack an ASP .NET website?  TO Hack an ASP .NET website?
TO Hack an ASP .NET website?
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guide
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation
 
Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in Scala
 
Kommons
KommonsKommons
Kommons
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 

More from joergreichert

OKLab Leipzig - 2023 Update
OKLab Leipzig - 2023 UpdateOKLab Leipzig - 2023 Update
OKLab Leipzig - 2023 Update
joergreichert
 
SDGs und wo sind die Daten?
SDGs und wo sind die Daten?SDGs und wo sind die Daten?
SDGs und wo sind die Daten?
joergreichert
 
Gieß a bit more the Bäume
Gieß a bit more the BäumeGieß a bit more the Bäume
Gieß a bit more the Bäume
joergreichert
 
OKLab Leipzig 2022
OKLab Leipzig 2022OKLab Leipzig 2022
OKLab Leipzig 2022
joergreichert
 
FAIRe Sensordaten
FAIRe SensordatenFAIRe Sensordaten
FAIRe Sensordaten
joergreichert
 
OKLab Leipzig 2021
OKLab Leipzig 2021OKLab Leipzig 2021
OKLab Leipzig 2021
joergreichert
 
Leipzig Giesst (Dezember 2020)
Leipzig Giesst (Dezember 2020)Leipzig Giesst (Dezember 2020)
Leipzig Giesst (Dezember 2020)
joergreichert
 
Road to mauAR
Road to mauARRoad to mauAR
Road to mauAR
joergreichert
 
OKLab Leipzig - Schwerpunkt Mobilität
OKLab Leipzig - Schwerpunkt MobilitätOKLab Leipzig - Schwerpunkt Mobilität
OKLab Leipzig - Schwerpunkt Mobilität
joergreichert
 
Die Stadt als Schule der Demokratie
Die Stadt als Schule der DemokratieDie Stadt als Schule der Demokratie
Die Stadt als Schule der Demokratie
joergreichert
 
OKLab Leipzig (2019 Update)
OKLab Leipzig (2019 Update)OKLab Leipzig (2019 Update)
OKLab Leipzig (2019 Update)
joergreichert
 
A Pattern Language - Patterns for Javascript
A Pattern Language - Patterns for JavascriptA Pattern Language - Patterns for Javascript
A Pattern Language - Patterns for Javascript
joergreichert
 
Unit testing mit Javascript
Unit testing mit JavascriptUnit testing mit Javascript
Unit testing mit Javascript
joergreichert
 
damals.in/leipzig
damals.in/leipzigdamals.in/leipzig
damals.in/leipzig
joergreichert
 
OkLab Leipzig (2018 Update)
OkLab Leipzig (2018 Update)OkLab Leipzig (2018 Update)
OkLab Leipzig (2018 Update)
joergreichert
 

More from joergreichert (15)

OKLab Leipzig - 2023 Update
OKLab Leipzig - 2023 UpdateOKLab Leipzig - 2023 Update
OKLab Leipzig - 2023 Update
 
SDGs und wo sind die Daten?
SDGs und wo sind die Daten?SDGs und wo sind die Daten?
SDGs und wo sind die Daten?
 
Gieß a bit more the Bäume
Gieß a bit more the BäumeGieß a bit more the Bäume
Gieß a bit more the Bäume
 
OKLab Leipzig 2022
OKLab Leipzig 2022OKLab Leipzig 2022
OKLab Leipzig 2022
 
FAIRe Sensordaten
FAIRe SensordatenFAIRe Sensordaten
FAIRe Sensordaten
 
OKLab Leipzig 2021
OKLab Leipzig 2021OKLab Leipzig 2021
OKLab Leipzig 2021
 
Leipzig Giesst (Dezember 2020)
Leipzig Giesst (Dezember 2020)Leipzig Giesst (Dezember 2020)
Leipzig Giesst (Dezember 2020)
 
Road to mauAR
Road to mauARRoad to mauAR
Road to mauAR
 
OKLab Leipzig - Schwerpunkt Mobilität
OKLab Leipzig - Schwerpunkt MobilitätOKLab Leipzig - Schwerpunkt Mobilität
OKLab Leipzig - Schwerpunkt Mobilität
 
Die Stadt als Schule der Demokratie
Die Stadt als Schule der DemokratieDie Stadt als Schule der Demokratie
Die Stadt als Schule der Demokratie
 
OKLab Leipzig (2019 Update)
OKLab Leipzig (2019 Update)OKLab Leipzig (2019 Update)
OKLab Leipzig (2019 Update)
 
A Pattern Language - Patterns for Javascript
A Pattern Language - Patterns for JavascriptA Pattern Language - Patterns for Javascript
A Pattern Language - Patterns for Javascript
 
Unit testing mit Javascript
Unit testing mit JavascriptUnit testing mit Javascript
Unit testing mit Javascript
 
damals.in/leipzig
damals.in/leipzigdamals.in/leipzig
damals.in/leipzig
 
OkLab Leipzig (2018 Update)
OkLab Leipzig (2018 Update)OkLab Leipzig (2018 Update)
OkLab Leipzig (2018 Update)
 

Recently uploaded

SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 

Recently uploaded (20)

SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 

Log4j2

  • 1.
  • 2. Tracing use cases Execution time system status current environment parameters issue recognition progress
  • 4. requirements easy to use API stackholder specific logs readable logs completenessperformance client specific logging (UI, console, build job) reliable correctness use case specific logging (production, testing, debugging) historic data relevant logs
  • 5. What to log • reporter (who discovered) • affected element • severity • message • issue code • additional data (e.g. exception object)
  • 6. Log levels • built-in: OFF, TRACE, DEBUG, INFO, WARN, ERROR, FATAL • Custom log levels • no level inheritance (as in log4j 1.x and logback), because separation of logger configuration and logger
  • 7. Log levels (2) <Configuration … status="INFO"> <Loggers> <Root level="INFO"> <AppenderRef ref="SYSERROUT" /> </Root> <Logger name="org.apache.logging.log4j2" level="INFO" /> <Logger name="my.package.MyIgnoreClass" level="OFF" /> </Loggers> </Configuration>
  • 8. Appenders <?xml version="1.0" encoding="UTF-8"?> <Configuration …> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> … </Console> … </Appenders> <Loggers> <Logger name="my.package"> <appender-ref ref="STDOUT" /> </Logger> </Loggers> </Configuration>
  • 9. Appenders • ConsoleAppender • FileAppender – RollingFileAppender – RandomAccessFileAppender • Messaging – JMSAppender – SMTPAppender • DB – JDBCAppender – JPAAppender – NoSQLAppender • Remote – SocketAppender – SyslogAppender
  • 10. Appenders • Wrapper – FailoverAppender – AsyncAppender <Async name="Async"> <AppenderRef ref="MyFile"/> </Async> – RoutingAppender .. explained later with MDC – RewriteAppender .. explained later with Message API
  • 12. Layout • PatternLayout • HTMLLayout • XMLLayout • JSONLayout • SerializedLayout
  • 13. Pattern Layout <PatternLayout pattern= " %date{dd.MM.yyyy HH:mm:ss,SSS} %5p %logger %m%n" /> %5p (oder %level) .. log level, maximal 5 Buchstaben, rechtbündig %logger .. logger name %c .. class name %m .. log message %n .. platform dependent line break %M .. class method
  • 14. Pattern Layout (2) • %t .. Name of the thread • xException["none"|"short"|"full"|depth],[filters(packages)} • xThrowable["none"|"short"|"full"|depth],[filters(packages)} • xEx{"none"|"short"|"full"|depth],[filters(packages)} – %xEx{short} .. Nur erste Zeile des Throwable – %xEx{n} .. n Zeilen – %xEx{none} oder %xEx{0} .. unterdrücken • MDC{key}  später erklärt
  • 15. Properties <?xml version="1.0" encoding="UTF-8"?> <Configuration …> <Properties> <Property name="defaultDatePattern"> %date{dd.MM.yyyy HH:mm:ss,SSS} </Property> <Property name="defaultLoggerPattern"> %5p %logger %marker %m%n </Property> <Property name="defaultLogPattern"> ${defaultDatePattern} ${defaultLoggerPattern} </Property> </Properties> … </Configuration>
  • 16. Nested Diagnostic Context (NDC) • stack • context is stored per thread • use push and pop to add and remove information NDC.push("processingLevel2"); log.info("success"); log4j.appender.CA.layout.ConversionPattern =%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %C %x = %m%n %x .. Accessing information
  • 17. Mapped Diagnostic Context (MDC) • context is stored per thread • MDC.put(), MDC.get(), and MDC.remove() MDC.put("userIP", req.getRemoteAddr()); MDC.put("userName", foo.getName()); log.info("success"); log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %X{userIP} %C %X{userName} = %m%n %X{userName} .. retrieves value for key "userName"
  • 18. Routing Appender <Console name="SYSERR"> … </Console> <Routing name="ConsoleAppenderRouteIssueCode"> <Routes pattern="${ctx:issueCode}"> <Route> <Console name="ConsoleAppenderWithIssueCode"> <PatternLayout pattern="${ctx:issueCode} - ${defaultLoggerPattern}"/> </Console> </Route> <Route ref="SYSERR" key="${ctx:issueCode}" /> </Routes> </Routing> … <AppenderRef ref="ConsoleAppenderRoute">
  • 20. Markers private static final Marker SQL_MARKER = MarkerManager.getMarker("SQL"); private static final Marker UPDATE_MARKER = MarkerManager.getMarker("SQL_UPDATE", SQL_MARKER); private static final Marker QUERY_MARKER = MarkerManager.getMarker("SQL_QUERY", SQL_MARKER); … logger.debug(QUERY_MARKER, "SELECT * FROM {}", table);
  • 21. Filters BurstFilter .. throttle logging when too many logs produced ThresholdFilter .. filters by log level ranges RegexFilter .. messages have to match regex MarkerFilter .. log event filter by marker resp. its sub type TimeFilter .. log only at certain times of day MapFilter .. filters by entries in MapMessage StructuredDataFilter .. special MapFilter DynamicThresholdFilter .. z.B. debug only for user id X ThreadContextMapFilter .. ThreadContext Map entries CompositeFilter .. apply multiple filters
  • 22. Regex Filter <?xml version="1.0" encoding="ASCII"?> <Configuration name=„MyLogger" …> … <Filters> <RegexFilter regex=".*stringToMatch.*" onMatch="DENY" onMismatch="NEUTRAL"/> </Filters> … </Configuration>
  • 23. Thread Context Map Filter <Loggers> … <Root level="error"> <AppenderRef ref="RollingFile"/> <ThreadContextMapFilter onMatch="ACCEPT" onMismatch="NEUTRAL" operator="or"> <KeyValuePair key="foo" value="bar"/> <KeyValuePair key="User2" value="WARN"/> </ThreadContextMapFilter> </Root> </Loggers>
  • 24. Message API • pass built-in or custom message objects • org.apache.logging.log4j.message – ParameterizedMessage – MapMessage – SimpleMessage – ObjectMessage – Message logger.info(new LoggedInMessage(map, user));
  • 25. Rewrite Logger logger = LogManager.getLogger(MyClass.class); Map<String, String> msg = new HashMap<String, String>(); msg.put("creditcard", "123456789"); logger.info(new MapMessage(msg));
  • 26. Rewrite (2) <Rewrite name="rewrite"> <AppenderRef ref="myweb"/> <MapRewritePolicy mode="Update"> <KeyValuePair key="creditcard" value="XXXXXXXXXX"/> </MapRewritePolicy> </Rewrite> <Logger …> <Appender-Ref ref="rewrite" /> </Logger> source: https://gomtiprabha.wordpress.com/2014/03/11/rewrite-appender-in-log4j2/
  • 27. Flow tracing public String method(String input) { logger.entry(input); … return logger.exit(); }
  • 28. package my.custom.log4j2.plugins; @Plugin(name = "Sandbox", type = "Core", elementType = "appender") public class SandboxAppender extends AppenderBase { private SandboxAppender(String name, Filter filter) { super(name, filter, null); } public void append(LogEvent event) { System.out.println(event.getMessage().getFormattedMessage()); } @PluginFactory public static SandboxAppender createAppender( @PluginAttr("name") String name, @PluginElement("filters") Filter filter) { return new SandboxAppender(name, filter); } } Plug-in infrastructure
  • 29. Plug-in infrastructure (2) <configuration … packages="my.custom.log4j2.plugins"> … <appenders> <Sandbox /> </appender> … </configuration>
  • 30. Reconfigure <?xml version="1.0" encoding="UTF-8"?> <configuration monitorInterval="30"> ... </configuration> • monitoring interval is a value in seconds • log4j 2 would reconfigure logging in case something has changed in your configuration • log4j 2.0 does not lose logging events at the time of reconfiguration
  • 31. XInclude <?xml version="1.0" encoding="UTF-8"?> <configuration …> <ThresholdFilter level="debug"/> <xi:include href="log4j-xinclude-appenders.xml" /> <xi:include href="log4j-xinclude-loggers.xml" /> </configuration>
  • 33. Logger configuration • Centralize • different context selectors – ThreadLocal – Classloader – JNDI – AsyncLogger • Make all loggers async – Bundle
  • 34. OSGi • Configure BundleContextSelector – associates LoggerContexts with the ClassLoader of the bundle that created the caller of the getLogger call • Own logger API and central logger config – Derive Eclipse plug-in project from log4j2 jars – Define fragment project to define your own logger API • In MANIFEST set – Eclipse-ExtensibleAPI: true
  • 35. Programmatic access -Dlog4j.configurationFile= ... LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(level); ctx.updateLoggers(); // loggers refetch information from their LoggerConfig
  • 36. Bad practice • logging errors that has been already handled by application code (e.g. failed login) • log messages with line breaks • non unified formatted log messages (no tabs) • long log messages (can be avoid by shorten the package name) • in tests use logging where assertions would have been a better choice (as they really enforce expected behavior where logs can be ignored) • not logging exception objects • using custom appenders holding state
  • 37. System.out.println(...) System.err.println(...) exception.printStackTrace() FileWriter writer = ...; writer.write(...); writer.close(); LOGGER.error(...) Bad practice (2)
  • 39. • use timestamps for every event • log thread name • log source of event (e.g. class name and message) • log ids from domain (e.g. transaction id) • concise and descriptive messages • use rolling file appender (to restrict single log file size) • log method inputs and output at debug resp. trace level • log full exception objects • log no more than necessary in production Good practice
  • 41. Log4J2 + Xtend Active Annotations @Delegate (built-in) to derive custom loggers with a few customized methods @Log to initialize instance log field with correct class as parameter @Traceable To annotate methods, so that logger.entry and logger.exit with input and output parameters are generated
  • 42. Links • Log4j2 • Apache Log4j 2.0 - Worth the Upgrade? • The new log4j 2.0 • The Logging Olympics – A Race Between Today’s Top 5 Java Logging Frameworks