SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Developing Faster with Swagger
Developing Faster with SwaggerDeveloping Faster with Swagger
Developing Faster with SwaggerTony Tam
 
Manual and Automation notes.pdf
Manual and Automation notes.pdfManual and Automation notes.pdf
Manual and Automation notes.pdfsynamedia
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface) Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface) Vibhawa Nirmal
 
Introduction to asp.net
Introduction to asp.netIntroduction to asp.net
Introduction to asp.netSHADAB ALI
 
TDC2015: Testes em APIs REST com Rest-Assured
TDC2015: Testes em APIs REST com Rest-AssuredTDC2015: Testes em APIs REST com Rest-Assured
TDC2015: Testes em APIs REST com Rest-AssuredJúlio de Lima
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Introducing Swagger
Introducing SwaggerIntroducing Swagger
Introducing SwaggerTony Tam
 
Swagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdfSwagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdfKnoldus Inc.
 
API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)Peter Thomas
 

Was ist angesagt? (20)

Developing Faster with Swagger
Developing Faster with SwaggerDeveloping Faster with Swagger
Developing Faster with Swagger
 
JDK,JRE,JVM
JDK,JRE,JVMJDK,JRE,JVM
JDK,JRE,JVM
 
Swagger
SwaggerSwagger
Swagger
 
C# File IO Operations
C# File IO OperationsC# File IO Operations
C# File IO Operations
 
Manual and Automation notes.pdf
Manual and Automation notes.pdfManual and Automation notes.pdf
Manual and Automation notes.pdf
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Automation Testing Syllabus - Checklist
Automation Testing Syllabus - ChecklistAutomation Testing Syllabus - Checklist
Automation Testing Syllabus - Checklist
 
Swagger UI
Swagger UISwagger UI
Swagger UI
 
Rest assured
Rest assuredRest assured
Rest assured
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface) Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface)
 
Introduction to asp.net
Introduction to asp.netIntroduction to asp.net
Introduction to asp.net
 
TDC2015: Testes em APIs REST com Rest-Assured
TDC2015: Testes em APIs REST com Rest-AssuredTDC2015: Testes em APIs REST com Rest-Assured
TDC2015: Testes em APIs REST com Rest-Assured
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
J2ee
J2eeJ2ee
J2ee
 
Introducing Swagger
Introducing SwaggerIntroducing Swagger
Introducing Swagger
 
Swagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdfSwagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdf
 
API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)
 
RESTful Web API
RESTful Web APIRESTful Web API
RESTful Web API
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Andere mochten auch

Mongo DB schema design patterns
Mongo DB schema design patternsMongo DB schema design patterns
Mongo DB schema design patternsjoergreichert
 
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 NXTjoergreichert
 
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 processesjoergreichert
 
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
 
Advanced language testing with XPECT
Advanced language testing with XPECTAdvanced language testing with XPECT
Advanced language testing with XPECTjoergreichert
 
Spray Democamp Dresden 2011-11-08
Spray Democamp Dresden 2011-11-08Spray Democamp Dresden 2011-11-08
Spray Democamp Dresden 2011-11-08joergreichert
 

Andere mochten auch (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
 

Ähnlich wie Log4j2

Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in ScalaKnoldus Inc.
 
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 EraSadayuki Furuhashi
 
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
 
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 StackJakub 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 logsStefan Krawczyk
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play FrameworkKnoldus 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 Loggingmitesh_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 customizationBartosz Konieczny
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guideAdy Liu
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortalJennifer Bourey
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - PresentationBiju Thomas
 
Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in ScalaKnoldus Inc.
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTPMustafa TURAN
 

Ähnlich wie 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 - 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
Docker Logging and analysing with Elastic StackDocker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic Stack
 
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
 

Mehr von joergreichert

OKLab Leipzig - 2023 Update
OKLab Leipzig - 2023 UpdateOKLab Leipzig - 2023 Update
OKLab Leipzig - 2023 Updatejoergreichert
 
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äumejoergreichert
 
Leipzig Giesst (Dezember 2020)
Leipzig Giesst (Dezember 2020)Leipzig Giesst (Dezember 2020)
Leipzig Giesst (Dezember 2020)joergreichert
 
OKLab Leipzig - Schwerpunkt Mobilität
OKLab Leipzig - Schwerpunkt MobilitätOKLab Leipzig - Schwerpunkt Mobilität
OKLab Leipzig - Schwerpunkt Mobilitätjoergreichert
 
Die Stadt als Schule der Demokratie
Die Stadt als Schule der DemokratieDie Stadt als Schule der Demokratie
Die Stadt als Schule der Demokratiejoergreichert
 
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 Javascriptjoergreichert
 
Unit testing mit Javascript
Unit testing mit JavascriptUnit testing mit Javascript
Unit testing mit Javascriptjoergreichert
 
OkLab Leipzig (2018 Update)
OkLab Leipzig (2018 Update)OkLab Leipzig (2018 Update)
OkLab Leipzig (2018 Update)joergreichert
 

Mehr von 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)
 

Kürzlich hochgeladen

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile EnvironmentVictorSzoltysek
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 

Kürzlich hochgeladen (20)

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 

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