Log4j 1.x with maven: minimal howto

This post is a minimal howto for log4j version 1.

What a simple task ! but who never search a simple sample on the web send a little stone to me ;)
Feel free to copy paste anyway ;))

What are the dependencies

You will need to add log4j, slf4j and lombok (to use @Slf4j) :

  <!--General project configuration -->

   <!-- @Slf4j annotation -->
   <!-- ## LOGS ## -->

How to use it

Simply add "@Slf4j" to your class, and then you could use "log" as logger.


import lombok.extern.slf4j.Slf4j;

public class MyClass {
    public MyClass() {
        log.debug("constructor YEP");
    public void doIt(long value) {"doIt {}", value);
        try {
            throw new InvalidParameterException("Zobby");
        } catch (Exception ee) {
            log.error("I'm so stupid: {} => {}", ee.getClass().getSimpleName(), ee.getMessage(), ee);
            log.warn("same without stack trace !: {} => {}", ee.getClass().getSimpleName(), ee.getMessage());

How to configure appenders

To configure log4j, add a file to your resources. Start by defining a console appender. This appender should appear in the rootLogger definition too. You could define the following content to start:

log4j.rootLogger=DEBUG, console

## Console appender 
log4j.appender.console.layout.ConversionPattern=%d %5p [%c{1}] %m%n

# package log levels
# Log4j bootstrap

How to configure file appender

Update your rootLoger to refer to the logfile appender, and add a logfile appender definition:

log4j.rootLogger=DEBUG, console, logfile

## File appender
log4j.appender.logfile.layout.ConversionPattern=%d{ISO8601} - %-5.5p - %t - %c - %m%n

How to configure graylog (splunk-like) appender

Update your rootLoger to refer to the graylog appender, and add a gelf appender definition:

### Graylog appender
log4j.appender.graylog2.graylogPort = 12201
#log4j.appender.graylog2.originHost=(default to the local hostname)
log4j.appender.graylog2.additionalFields={'environment': '${projectEnvironment}', 'application': 'MyPoc','version': '${buildVersion}_${buildTimestamp}'}

How to configure NT event appender

Pre-requisites : add NTEventLogAppender.dll and NTEventLogAppender.amd64.dll to the current directory or to the java ld library path. You could append "-Djava.library.path=PATH" to your application if needed. Get this dll files from log4j zip distribution  doc :

Update your rootLoger to refer to the ntappender appender, and add a new ntappender definition:

# NTEventLogAppender
log4j.appender.ntappender.layout.ConversionPattern=%d{ISO8601} - %-5.5p - %t - %c - %m%n

For this last usecase you will be able to see the app logs into Windows Event Log service :

Aucun commentaire:

Enregistrer un commentaire

Mots clés du blog

acceptancetest androï Android androïd Android7 api appender appengine application applications archive array assistantematernelle astuce auth0 authentication authority automation Axis bash bearer blog bower build bundle c calendrier camille combal cdi certificate cf client cloudfoundry collaboratif command commandes connexion console css démasquées démasquer développement dll dump easter eggs écologie écrit employeur EMUI EMUI5.0 enfant évènement export-package ExtJS fiche find firefox gadget gelf gem git gmail gooelappengine google gparted gps graylog grenoble Grid gui harddrive heroku hover howto HTML http https IE ihm immobilier imprimante innovation insolite instance integration Java JavaScript jenkins jeu jobs json json-schema-validator key keystore labs linux livre log log4j logger logs lombok masquées masquer maven maven-gae-plugin Mémoire microsoft mobile mockito mondialisation monitor MUSE musique en ligne myopera nodejs npm NT NTEventLogger onglet openstack osgi paas package parameters parent php politique prosyst prototype proxies proxy quartz radio rappel recherche regex repository resize RIA rock route ruby rubygems s8500 samsung scheduler scm sel selenium Serializer server shared shell slf4j smartphone so société song spy ssh ssl struct swagger swig tâches téléphone téléréalité test thunderbird timeout token Tomcat tooltip tooltips truststore ubuntu unit test validator virgin virtualbox wave waze web WebApp wiki wikimedia wikipédia wikipen windows yahoo youtube yum