Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Log4j setting in Maven project

    • 0
    • 2
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 606
    Comment on it

    As per maven project structure, there is a resource folder where all application related properties will be added. Implementation of log4j in MAVEN application,

    Create log4j.properties file inside resource folder and paste below code lines:

    # Direct log messages to a log file
    log4j.appender.file=org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=${catalina.base}/logs/<loge-file-name>.log
    #log4j.appender.file.Append=true
    log4j.appender.file.MaxFileSize=100MB
    log4j.appender.file.MaxBackupIndex=1
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    # Direct log messages to stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    # Root logger option
    log4j.rootLogger=DEBUG, file
    

    As you can see in 2nd line where we define log4j.appender.file.File, you can write any name for your log file. Here we used for reference. This file will create inside your tomcat logs folder.

    Now open pom.xml file and add dependency for log4j inside tag.

    <dependency>
           <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.8</version>
    </dependency>
    

    In controller side, to use Logger in controller,

    First you include classes for Logger import org.apache.log4j.Logger;

    Create a Logger instance

    private static final Logger logger = Logger.getLogger(<your_class_name>.class);
    @RequestMapping("/addStudentRecord")
    public ModelAndView showMessage() {  
        System.out.println("from controller");  
        logger.debug("Welcome to logger world >> DEBUG");
        logger.info("Welcome to logger world >> INFO");
        logger.warn("Welcome to logger world >> WARN");
        logger.error("Welcome to logger world >> ERROR");
        return new ModelAndView("addStudentRecord", "message", message);  
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: