rss

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) :

 <properties>
  <!--General project configuration -->
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

  <lombok.version>1.16.6</lombok.version>
  <log4j.version>1.2.17</log4j.version>
  <slf4j.version>1.7.10</slf4j.version>
  <junit.version>4.12</junit.version>
 </properties>
 <dependencyManagement>
  <dependencies>
   <!-- @Slf4j annotation -->
   <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok.version}</version>
    <scope>provided</scope>
   </dependency>
   <!-- ## LOGS ## -->
   <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4j.version}</version>
   </dependency>
   <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
   </dependency>
   <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j.version}</version>
   </dependency>

How to use it

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

import java.security.InvalidParameterException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyClass {
    public MyClass() {
        log.debug("constructor YEP");
    }
    
    public void doIt(long value) {
        log.info("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 log4j.properties 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=org.apache.log4j.ConsoleAppender
log4j.appender.console.threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %5p [%c{1}] %m%n

# package log levels
#
# Log4j bootstrap
#
log4j.logger.org.apache.http = INFO
log4j.logger.com.myapp = DEBUG
#

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=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.threshold=DEBUG
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{ISO8601} - %-5.5p - %t - %c - %m%n
log4j.appender.logfile.file=MY_CUSTOMFILEHERE.log
log4j.appender.logfile.maxBackupIndex=5
log4j.appender.logfile.maxFileSize=2048KB
log4j.appender.logfile.append=true

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=org.graylog2.log.GelfAppender
log4j.appender.graylog2.graylogHost=tcp:mygraylogserver.net
log4j.appender.graylog2.graylogPort = 12201
#log4j.appender.graylog2.originHost=(default to the local hostname)
log4j.appender.graylog2.facility=gelf-java
log4j.appender.graylog2.layout=org.apache.log4j.PatternLayout
log4j.appender.graylog2.extractStacktrace=true
log4j.appender.graylog2.addExtendedInformation=true
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 : https://wiki.apache.org/logging-log4j/NTEventLogAppender

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

# NTEventLogAppender
log4j.appender.ntappender=org.apache.log4j.nt.NTEventLogAppender
log4j.appender.ntappender.Source=MyKillerApp
log4j.appender.ntappender.layout=org.apache.log4j.PatternLayout
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