Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback's architecture.

Overview

Apache Log4j 2

Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback's architecture.

Jenkins build (3.x) Jenkins build (2.x) GitHub build (3.x) GitHub build (2.x) Latest Maven Central release

Pull Requests on Github

By sending a pull request you grant the Apache Software Foundation sufficient rights to use and release the submitted work under the Apache license. You grant the same rights (copyright license, patent license, etc.) to the Apache Software Foundation as if you have signed a Contributor License Agreement. For contributions that are judged to be non-trivial, you will be asked to actually sign a Contributor License Agreement.

Usage

Users should refer to Maven, Ivy, Gradle, and SBT Artifacts on the Log4j web site for instructions on how to include Log4j into their project using their chosen build tool.

Basic usage of the Logger API:

package com.example;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

public class Example {
    private static final Logger LOGGER = LogManager.getLogger();

    public static void main(String... args) {
        String thing = args.length > 0 ? args[0] : "world";
        LOGGER.info("Hello, {}!", thing);
        LOGGER.debug("Got calculated value only if debug enabled: {}", () -> doSomeCalculation());
    }

    private static Object doSomeCalculation() {
        // do some complicated calculation
    }
}

And an example log4j2.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="com.example" level="INFO"/>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

Documentation

The Log4j 2 User's Guide is available here or as a downloadable PDF.

Requirements

Log4j 2.4 and greater requires Java 7, versions 2.0-alpha1 to 2.3 required Java 6. Some features require optional dependencies; the documentation for these features specifies the dependencies.

License

Apache Log4j 2 is distributed under the Apache License, version 2.0.

Download

How to download Log4j, and how to use it from Maven, Ivy and Gradle. You can access the latest development snapshot by using the Maven repository https://repository.apache.org/snapshots, see Snapshot builds.

Issue Tracking

Issues, bugs, and feature requests should be submitted to the JIRA issue tracking system for this project.

Pull request on GitHub are welcome, but please open a ticket in the JIRA issue tracker first, and mention the JIRA issue in the Pull Request.

Building From Source

Log4j requires Apache Maven 3.x. To build from source and install to your local Maven repository, execute the following:

mvn install

Contributing

We love contributions! Take a look at our contributing page.

Comments
  • Import of LogstashLayout as JsonTemplateLayout

    Import of LogstashLayout as JsonTemplateLayout

    This is the very first draft of my work on contributing log4j2-logstash-layout into Log4j core. Please note that this is still a work in progress. I want to have your feedback and support on the following issues which I will share below.

    Goals

    Below is the list of goals I plan to deliver in order:

    • [X] Update manual
    • [X] Replace Uris with LoaderUtils
    • [X] Add directive for "nanos of epoch millis", "millis of epoch seconds", etc.
    • [X] Move pattern, timeZone, locale parameters into timestamp key level.
    • [ ] Add benchmark to log4j-perf
    • [X] Rename log4j-layout-jackson-json-template to log4j-layout-json-template
    • [X] Replace TLAs with a user-provided 3-way caching strategy

    I will update this list upon progress.

    Module and package name

    I chose JsonTemplateLayout as the new module name, which clearly communicates the intent. I am not totally convinced with the package name o.a.l.log4j.jackson.json.template.layout though. I have my doubts about whether we can remove Jackson dependency in the future or not. This ambition does look neither feasible, nor practical in the short-term. That said, from an API perspective, why shall an internal detail like jackson get exposed in the package name? I am considering to place it under o.a.l.log4j.layout.json.template. Any ideas?

    Documentation

    LogstashLayout has quite some configuration knobs which renders it inconvenient to explain it in /src/site/asciidoc/manual/layouts.adoc. I have skimmed through the source code with the hope of finding a similar documentation pattern, but failed to do so. Would somebody mind shedding some light onto the convention I should follow here, please?

    MapMessage#getFormattedMessage() JSON encoding bug

    As reported in LOG4J2-2703, MapMessage#getFormattedMessage() is incorrectly formatting Objects for JSON. As a workaround in LogstashLayout, I had a LogstashLayout.Builder#mapMessageFormatterIgnored property, which I have dragged into JsonTemplateLayout.Builder too. The property instructs the layout to ignore MapMessage#getFormattedMessage() and do its own magic to properly encode the MapMessage into JSON. Shall I keep this ad-hoc fix or rather resolve LOG4J2-2703 first?

    Performance tests

    I have some test utility classes that I want to leverage in performance tests, but test classpath of log4j-jackson-json-template module is not accessible by log4j-perf module. What is the work around here?

    What to do with JsonLayout?

    I do not intend to implement JsonLayout by leveraging JsonTemplateLayout, at least, not now. I would rather just leave it be and get deprecated eventually. Put another way, is this PR the right place to address this issue?

    Missing features compared to JsonLayout

    You might have noticed that JsonTemplateLayout misses certain features (e.g., compact, complete, header, footer, etc.) compared to JsonLayout. This is a deliberate decision of mine. If you have any objections, please chime in.

    Thread locals

    Even though the existing TLA usage of LogstashLayout is dragged in, I am going to replace it with an object pool. I have spotted ThreadLocalVsPoolBenchmark and will start from there.

    opened by vy 40
  • LOG4J2-3259: Limit max recursion depth when interpolating strings.

    LOG4J2-3259: Limit max recursion depth when interpolating strings.

    I've hard coded the limit to 10. If you feel the limit needs to be configurable (via system property or the log4j config?), let me know and I'll adjust.

    I couldn't find a good way to keep the call in line 987 to the protected method rather than the private method, while also keeping track of the recursion count. I'm not sure if that call is relied on by subclasses, I don't think the Javadoc promises a call to that method for each variable resolved.

    opened by srdo 30
  • [LOG4J2-928] Mostly wait-free MemoryMappedFileManager

    [LOG4J2-928] Mostly wait-free MemoryMappedFileManager

    A pull request for https://issues.apache.org/jira/browse/LOG4J2-928.

    This PR is not complete - it lacks tests and benchmarks (I'm going to add them in the next few weeks), but the core implementation is reviewable already.

    opened by leventov 30
  • Proposed fix for LOG4J2-2610 rollover issue:

    Proposed fix for LOG4J2-2610 rollover issue:

    Proposed fix for LOG4J2-2610 rollover issue:

    • Fix for Windows Filesystem Tunneling issue, rapid rollover issue.
    • Added FileUtils.updateFileCreationTime() method.
    • Updated FileManager and RollingFileManager to allow the file creationTime attribute to be updated on rollover (when it doesn't match initialTime).
    • RollingAppenderSizeWithTimeTest.testAppender() was failing on Windows before any changes. Rapid log rollover was causing overwrite of data in some cases (instead of writing to a new log file), resulting in lost logging messages. Mitigation was to apply a 1ms sleep in RollingFileManager.createFileAfterRollover().
    opened by JCgH4164838Gh792C124B5 25
  • JsonLayout support for custom key-value pairs being inserted into JSON

    JsonLayout support for custom key-value pairs being inserted into JSON

    Note: This is not ready PR, there are no unit tests for new feature - please review before i'll invest more time into it.

    • Changed AbstractJacksonLayout.convertMutableToLog4jEvent to protected Object wrapLogEvent(LogEvent event)
    • Added Extras as KeyValuePair[] to JsonLayout
    • When extras as specified, LogEvent is wrapped in new LogEventWithAdditionalFields class, which merges LogEvent serialized data with provided extras

    This is generally wanted feature, for example see here: https://github.com/ggrandes/log4j2-simplejson https://github.com/majikthys/log4j2-logstash-jsonevent-layout

    How it works:

    <JsonLayout>
      <KeyValuePair key="hostName" value="${hostName}"/>
    </JsonLayout>
    

    Inserts into each generated JSON hostName key:

    {
    "timeMillis":1505228896690,
    "thread":"main",
    "level":"INFO",
    "loggerName":"org.springframework....",
    "message":"Refreshing ...",
    "endOfBatch":false,
    "loggerFqcn":"org....",
    "contextMap":{},
    "threadId":1,
    "threadPriority":5,
    "hostName":"wp21257b"
    }
    

    This is accomplished by tricks with Jackon json serializer:

    public static class LogEventWithAdditionalFields {
        // ....
        @JsonUnwrapped // Deserializes actual LogEvent into root object
        public Object getLogEvent() { return logEvent; }
    
        @JsonAnyGetter // Adds everything from the map into root object
        public Map<String, Object> getAdditionalFields() { return additionalFields; }
    }
    
    opened by mdvorak 23
  • Add a new LuceneAppender which writes logging events to a lucene index library.

    Add a new LuceneAppender which writes logging events to a lucene index library.

    Add a new LuceneAppender which writes logging events to a lucene index library.The log4j2.xml configuration is as follows: <Lucene name="lucene" ignoreExceptions="true" target="/target/lucene/index" expiryTime=“1296000”> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/> <IndexField name="time" pattern="%d{UNIX_MILLIS}" type="LongField"/> <IndexField name="level" pattern="%-5level" /> <IndexField name="content" pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/> </Lucene>

    this appender relies on the Lucene 5.5.4 version. this patch adds the corresponding test cases.

    opened by liyuj 19
  • Property log4j.skipJansi should have a default of true

    Property log4j.skipJansi should have a default of true

    The current default forces Win platforms to install an obscure jansi native library (for pretty print console messages) or always set this property to true, even for trivial unit tests.

    opened by AndyGee 18
  • Initial support for detached markers in SLF4J binding

    Initial support for detached markers in SLF4J binding

    Hello all,

    please accept this small patch from a long time user of log4j: it will enable using log4j 2.x in several applications here at @six-group.com!

    This proposal allows creating detached Markers as specified by the IMarkerFactory interface. A detached marker allows the caller to inject non-constant data that can be used to implement structured logging (my use-case). Because of this, they cannot be cached in Log4jMarkerFactory.markerMap or converted.

    Please let me know if you require additional modifications (e.g. unit tests perhaps?)

    opened by dfa1 17
  • LOG4J2-3004 Add plugin support to JsonTemplateLayout.

    LOG4J2-3004 Add plugin support to JsonTemplateLayout.

    This change set aims to replace statically bound JSON template resolver factories with plugins. Along this pursuit, following side kicks are introduced:

    • Added support for inline stack trace element templates in exception and exceptionRootCause resolvers.
    • Added PluginUtil class.
    • Updated TypeConverterRegistry to handle competing converters for the same type.

    Judging from the json-template-layout.html generated via ./mvnw site -DskipTests=true -Dmaven.doap.skip=true, there is an AsciiDoc puzzler waiting to be addressed: usage of xref:event-template-resolver-exception[] and xref:event-template-resolver-exceptionRootCause[] renders garbled text and link.

    opened by vy 14
  • [LOG4J2-2400] Initial implementation of RedisAppender.

    [LOG4J2-2400] Initial implementation of RedisAppender.

    This PR implements a dedicated RedisAppender in log4j2. More details can be found in the log4j2 ticket here: https://issues.apache.org/jira/projects/LOG4J2/issues/LOG4J2-2400?filter=allopenissues

    opened by nataliemeurer 14
  • [LOG4J2-1838] Print common suffix to each line of a Throwable stack trace

    [LOG4J2-1838] Print common suffix to each line of a Throwable stack trace

    This pull request will allow us to print a common suffix to each line of the stack trace of a throwable event.

    The suffix can be configured with normal patterns (But patterns that can handle Throwable will be auto removed from here, because the rendered effect will be confusing with them).

    For example, pattern %xEx{suffix(%X{mdc_key})} will append the MDC value to key mdc_key to each line of the stack track.

    But for pattern %xEx{suffix(%xEx)}, the nested %xEx pattern will be ignored.

    opened by xnslong 14
  • LOG4J2-1631 Honor timezone in file name pattern

    LOG4J2-1631 Honor timezone in file name pattern

    Given pattern "app-%d{yyyy-MM-dd}{timezone}.log.gz" treat second pair of curly braces as timezone option.

    If timezone option is not set, then use default timezone as before. If timezone option is set, but it's parsing fails, then use GMT+0. (same DatePatternConverter behavior as in other places)

    opened by dnsmkl 0
  • Simplify site generation

    Simplify site generation

    Warning! These changes are based on the work delivered in #1145 replacing the maven-changes-plugin. Hence, that PR needs to be merged first!

    This PR attempts to simplify the site generation. Highlights from the changes are as follows:

    1. all Maven reporting is disabled
    2. Coveralls, JaCoCo, DOAP, PDF configurations are removed
    3. enforce-upper-bound-deps Maven enforcer rule is fixed
    4. /pom.xml is overhauled (developers are simplified, contributors are removed, unused configurations/properties are removed, etc.)
    5. maven-site-plugin is disabled for all modules except /pom.xml
    6. all <module>/src/site/markdown/index.md[.vm] files are moved to /src/site/markdown/<module>.md[.vm]
    7. build instructions are updated

    As a result, ./mvnw site takes less than 30s on a decent laptop.

    opened by vy 7
  • [LOG4J2-3642] Consider Osgi versions older than 1.5 as not available.

    [LOG4J2-3642] Consider Osgi versions older than 1.5 as not available.

    We use the method FrameworkUtil.getBundle from OSGi, but this method was added only in OSGi 1.5, this causes NoSuchMethodError if older version of OSGi is used.

    I would suggest to consider OSGi being unavailable for OSGi version < 1.5 or when that method is not available.

    opened by adwsingh 9
  • Disclose relationship with TideLift

    Disclose relationship with TideLift

    This is a draft of the changes to the Support page to disclose the relationship of some PMCs with TideLift.

    Personally I don't mind disclosing the names of the people involved, if the other PMCs prefer it this way.

    opened by ppkarwasz 0
  • Bump maven-dependency-plugin from 3.3.0 to 3.4.0

    Bump maven-dependency-plugin from 3.3.0 to 3.4.0

    Bumps maven-dependency-plugin from 3.3.0 to 3.4.0.

    Commits
    • 8fecf8a [maven-release-plugin] prepare release maven-dependency-plugin-3.4.0
    • f2e192a [MDEP-809] Fix JavaDoc for verbose parameter of tree mojo
    • f9b3ab7 Bump plexus-utils from 3.4.2 to 3.5.0
    • e741282 Refresh setup-custom-ear-lifecycle test
    • a3c64de Fix tests for new plexus-archiver
    • d78f6e1 Bump plexus-archiver from 4.2.2 to 4.6.0
    • 50a4b70 [MDEP-674] Add IDE build support (#257)
    • 0eabeef Bump project version to 3.4.0-SNAPSHOT
    • b8af16f Bump mockito-core from 4.8.1 to 4.9.0
    • 23bfa03 Bump maven-dependency-tree from 3.2.0 to 3.2.1
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies java 
    opened by dependabot[bot] 0
Owner
The Apache Software Foundation
The Apache Software Foundation
Echopraxia - Java Logging API with clean and simple structured logging and conditional & contextual features. Logback implementation based on logstash-logback-encoder.

Echopraxia Echopraxia is a Java logging API that and is designed around structured logging, rich context, and conditional logging. There is a Logback-

Terse Systems 43 Nov 30, 2022
Sidekick is a live application debugger that lets you troubleshoot your applications while they keep on running

Explore Docs » Quick Start Tutorial » Table of Contents What is Sidekick? Sidekick Actions Why Sidekick? Features Who should use Sidekick? How does Si

Sidekick 1.6k Jan 6, 2023
reload4j is a drop-in replacement for log4j 1.2.17

What is reload4j? The reload4j project is a fork of Apache log4j version 1.2.17. It aims to fix the most urgent issues in log4j 1.2.17 which hasn't se

QOS.CH (Switzerland) 122 Dec 15, 2022
A high performance replicated log service. (The development is moved to Apache Incubator)

Apache DistributedLog (incubating) Apache DistributedLog (DL) is a high-throughput, low-latency replicated log service, offering durability, replicati

Twitter 2.2k Dec 29, 2022
A Java library that facilitates reading, writing and processing of sensor events and raw GNSS measurements encoded according to the Google's GNSS Logger application format.

google-gnss-logger This library facilitates reading, writing and processing of sensor events and raw GNSS measurements encoded according to the Google

Giulio Scattolin 5 Dec 21, 2022
An extensible Java library for HTTP request and response logging

Logbook: HTTP request and response logging Logbook noun, /lɑɡ bʊk/: A book in which measurements from the ship's log are recorded, along with other sa

Zalando SE 1.3k Dec 29, 2022
P6Spy is a framework that enables database data to be seamlessly intercepted and logged with no code changes to the application.

p6spy P6Spy is a framework that enables database data to be seamlessly intercepted and logged with no code changes to existing application. The P6Spy

p6spy 1.8k Dec 27, 2022
Best-of-breed OpenTracing utilities, instrumentations and extensions

OpenTracing Toolbox OpenTracing Toolbox is a collection of libraries that build on top of OpenTracing and provide extensions and plugins to existing i

Zalando SE 181 Oct 15, 2022
Logstash - transport and process your logs, events, or other data

Logstash Logstash is part of the Elastic Stack along with Beats, Elasticsearch and Kibana. Logstash is a server-side data processing pipeline that ing

elastic 13.2k Jan 5, 2023
Free and open source log management

Graylog Welcome! Graylog is an open source log management platform. You can read more about the project on our website and check out the documentation

Graylog 6.4k Jan 6, 2023
The reliable, generic, fast and flexible logging framework for Java.

About logback Thank you for your interest in logback, the reliable, generic, fast and flexible logging library for Java. The Logback documentation can

QOS.CH Sarl 2.6k Jan 7, 2023
tinylog is a lightweight logging framework for Java, Kotlin, Scala, and Android

tinylog 2 Example import org.tinylog.Logger; public class Application { public static void main(String[] args) { Logger.info("Hello

tinylog.org 547 Dec 30, 2022
Best-of-breed OpenTracing utilities, instrumentations and extensions

OpenTracing Toolbox OpenTracing Toolbox is a collection of libraries that build on top of OpenTracing and provide extensions and plugins to existing i

Zalando SE 181 Oct 15, 2022
Log sourcing is method of trying to map all the ERROR and WARN logs you have in your system in a cost effective way.

log-sourcing Log sourcing is method of trying to map all the ERROR and WARN logs you have in your system in a cost effective way. The basic idea is th

Shimon Magal 12 Apr 19, 2021
tinylog is a lightweight logging framework for Java, Kotlin, Scala, and Android

tinylog 2 Example import org.tinylog.Logger; public class Application { public static void main(String[] args) { Logger.info("Hello

tinylog.org 551 Jan 4, 2023
Logging filters for Spring WebFlux client and server request/responses

webflux-log Logging filters for Spring WebFlux client and server request/responses. Usage To log WebClient request/response, do the following specify

null 10 Nov 29, 2022
PortalLogger - Logs portals into a text file and in chat

Logs portals into a text file and in chat. Useful if afk flying under bedrock. Feel free to add to your client The logs are stored in .minecraft/ARTEMIS/PortalLogger

null 7 Dec 2, 2022
Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor

Apache Log4j 2 Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the

Alvaro Muñoz 5 Oct 21, 2022
Echopraxia - Java Logging API with clean and simple structured logging and conditional & contextual features. Logback implementation based on logstash-logback-encoder.

Echopraxia Echopraxia is a Java logging API that and is designed around structured logging, rich context, and conditional logging. There is a Logback-

Terse Systems 43 Nov 30, 2022