Hibernate Logging by Log4j using properties file

Log4j and Logback frameworks are used to support logging in hibernate, there are two ways to perform logging using log4j:

  1. By log4j.xml file (or)
  2. By log4j.properties file

Here, we are going to enable logging using log4j through properties file.

Create log4j.properties file

Now you need to create log4j.properties file. In this example, all the log details will be written in the D:\\logfilename.log file.( location where you want)

if you want logs present inside log folder which are created inside the src folder then write 

logs/logfilename.log

# Direct log messages to a log file

log4j.appender.file=org.apache.log4j.RollingFileAppender

#log4j.appender.file.File=D:\\javatpointhibernate.log

# Define the log folder path

log4j.appender.file.File=logs/javatpointhibernate.log


log4j.appender.file.MaxFileSize=1MB

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.Target=System.out

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=INFO, file, stdout

# Log everything. Good for troubleshooting

log4j.logger.org.hibernate=INFO

# Log all JDBC parameters

log4j.logger.org.hibernate.type=ALL

#logging.path=logs


package com.hbm;


import org.apache.log4j.Logger;


public class Testapp {


// It's a good practice to use camelCase for class names (TestApp instead of Testapp)

private static Logger logger = Logger.getLogger(Testapp.class);


public static void main(String[] args) {


// Create a SimpleLayout for logging output

// Layout layout = new SimpleLayout();

//Layout layout = new SimpleLayout();

// Use PatternLayout with a time pattern

// Layout layout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n");

// Layout layout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%t] %c{1}.%M(%F:%L) - %m%n");

// Use a ConsoleAppender to output log messages to the console

// Appender appender = new ConsoleAppender(layout);


// Set the appender to the logger

//log.addAppender(appender);


// Log various messages with different log levels

// log.info("from info");

// log.debug("from debug");

// log.fatal("from fatal");

// log.error("from error"); // Corrected the log message

// log.warn("from warn");

// Log statements

logger.debug("Debug message");

logger.info("Info message");

logger.warn("Warning message");

logger.error("Error message");

}

}



Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence