Log4J error : Please initialize the log4j system properly [duplicate] - spring

After adding log4j to my application I get the following output every time I execute my application:
log4j:WARN No appenders could be found for logger (slideselector.facedata.FaceDataParser).
log4j:WARN Please initialize the log4j system properly.
It seems this means a configuration file is missing.
Where should this config file be located and what is a good start content?
I'm using plain java for developing a desktop application. So no webserver etc...

Log4j by default looks for a file called log4j.properties or log4j.xml on the classpath.
You can control which file it uses to initialize itself by setting system properties as described here (Look for the "Default Initialization Procedure" section).
For example:
java -Dlog4j.configuration=customName ....
Will cause log4j to look for a file called customName on the classpath.
If you are having problems I find it helpful to turn on the log4j.debug:
-Dlog4j.debug
It will print to System.out lots of helpful information about which file it used to initialize itself, which loggers / appenders got configured and how etc.
The configuration file can be a java properties file or an xml file. Here is a sample of the properties file format taken from the log4j intro documentation page:
log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

While setting up log4j properly is great for "real" projects you might want a quick-and-dirty solution, e.g. if you're just testing a new library.
If so a call to the static method
org.apache.log4j.BasicConfigurator.configure();
will setup basic logging to the console, and the error messages will be gone.

If you just get rid of everything (e.g. if you are in tests)
org.apache.log4j.BasicConfigurator.configure(new NullAppender());

As per Apache Log4j FAQ page:
Why do I see a warning about "No appenders found for logger" and "Please configure log4j properly"?
This occurs when the default configuration files log4j.properties and log4j.xml can not be found and the application performs no explicit configuration. log4j uses Thread.getContextClassLoader().getResource() to locate the default configuration files and does not directly check the file system. Knowing the appropriate location to place log4j.properties or log4j.xml requires understanding the search strategy of the class loader in use. log4j does not provide a default configuration since output to the console or to the file system may be prohibited in some environments.
Basically the warning No appenders could be found for logger means that you're using log4j logging system, but you haven't added any Appenders (such as FileAppender, ConsoleAppender, SocketAppender, SyslogAppender, etc.) into your configuration file or the configuration file is missing.
There are three ways to configure log4j: with a properties file (log4j.properties), with an XML file and through Java code (rootLogger.addAppender(new NullAppender());).
log4j.properties
If you've property file present (e.g. when installing Solr), you need to place this file within your classpath directory.
classpath
Here are some command suggestions in Linux how to determine your classpath value:
$ echo $CLASSPATH
$ ps wuax | grep -i classpath
$ grep -Ri classpath /etc/tomcat? /var/lib/tomcat?/conf /usr/share/tomcat?
or from Java: System.getProperty("java.class.path").
Log4j XML
Below is a basic XML configuration file for log4j in XML format:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<root>
<priority value ="debug" />
<appender-ref ref="console" />
</root>
</log4j:configuration>
Tomcat
If you're using Tomcat, you may place your log4j.properties into: /usr/share/tomcat?/lib/ or /var/lib/tomcat?/webapps/*/WEB-INF/lib/ folder.
Solr
For the reference, Solr default log4j.properties file looks like:
# Logging level
solr.log=logs/
log4j.rootLogger=INFO, file, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x \u2013 %m%n
#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9
#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n
log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN
# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF
Why can't log4j find my properties file in a J2EE or WAR application?
The short answer: the log4j classes and the properties file are not within the scope of the same classloader.
Log4j only uses the default Class.forName() mechanism for loading classes. Resources are handled similarly. See the documentation for java.lang.ClassLoader for more details.
So, if you're having problems, try loading the class or resource yourself. If you can't find it, neither will log4j. ;)
See also:
Short introduction to log4j at Apache site
Apache: Logging Services: FAQ at Apache site

Find a log4j.properties or log4j.xml online that has a root appender, and put it on your classpath.
### 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.SimpleLayout
log4j.rootLogger=debug, stdout
will log to the console. I prefer logging to a file so you can investigate afterwards.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.maxFileSize=100KB
log4j.appender.file.maxBackupIndex=5
log4j.appender.file.File=test.log
log4j.appender.file.threshold=debug
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=debug,file
although for verbose logging applications 100KB usually needs to be increased to 1MB or 10MB, especially for debug.
Personally I set up multiple loggers, and set the root logger to warn or error level instead of debug.

You can set the location of your log4j.properties from inside your java app by using:
org.apache.log4j.PropertyConfigurator.configure(file/location/log4j.properties)
More information is available here: https://logging.apache.org/log4j/1.2/manual.html

Another way to do it without putting the property file on the classpath, is to set the property from the java code directly. Here is the sample code.
public class Log4JSample {
public static void main(String[] args) {
Properties properties=new Properties();
properties.setProperty("log4j.rootLogger","TRACE,stdout,MyFile");
properties.setProperty("log4j.rootCategory","TRACE");
properties.setProperty("log4j.appender.stdout", "org.apache.log4j.ConsoleAppender");
properties.setProperty("log4j.appender.stdout.layout", "org.apache.log4j.PatternLayout");
properties.setProperty("log4j.appender.stdout.layout.ConversionPattern","%d{yyyy/MM/dd HH:mm:ss.SSS} [%5p] %t (%F) - %m%n");
properties.setProperty("log4j.appender.MyFile", "org.apache.log4j.RollingFileAppender");
properties.setProperty("log4j.appender.MyFile.File", "my_example.log");
properties.setProperty("log4j.appender.MyFile.MaxFileSize", "100KB");
properties.setProperty("log4j.appender.MyFile.MaxBackupIndex", "1");
properties.setProperty("log4j.appender.MyFile.layout", "org.apache.log4j.PatternLayout");
properties.setProperty("log4j.appender.MyFile.layout.ConversionPattern","%d{yyyy/MM/dd HH:mm:ss.SSS} [%5p] %t (%F) - %m%n");
PropertyConfigurator.configure(properties);
Logger logger = Logger.getLogger("MyFile");
logger.fatal("This is a FATAL message.");
logger.error("This is an ERROR message.");
logger.warn("This is a WARN message.");
logger.info("This is an INFO message.");
logger.debug("This is a DEBUG message.");
logger.trace("This is a TRACE message.");
}
}

import org.apache.log4j.BasicConfigurator;
Call this method
BasicConfigurator.configure();

You can set up the log level by using setLevel().
The levels are useful to easily set the kind of informations you want the program to display.
For example:
Logger.getRootLogger().setLevel(Level.WARN); //will not show debug messages
The set of possible levels are:
TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL
According to Logging Services manual

To enable -Dlog4j.debug, I go to System, Advanced system settings, Environment variables and set system variable _JAVA_OPTIONS to -Dlog4j.debug.

What are you developing in? Are you using Apache Tomcat?
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyyMMdd HH:mm:ss.SSS} [[%5p] %c{1} [%t]] %m%n
I have a properties like this in a Java app of mine.

I've created file log4j.properties in resources folder next to hibernate.cfg.xml file and filled it with text below:
log4j.rootLogger=INFO, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}:%L] %m%n
now I got rid of warnings and errors

Simply, create log4j.properties under src/main/assembly folder. Depending on if you want log messages to be shown in the console or in the file you modify your file. The following is going to show your messages in the console.
# Root logger option
log4j.rootLogger=INFO, stdout
# 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{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

My log4j got fixed by below property file:
## 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.SimpleLayout
log4j.rootLogger=debug, stdout
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.maxFileSize=100KB
log4j.appender.file.maxBackupIndex=5
log4j.appender.file.File=./logs/test.log
log4j.appender.file.threshold=debug
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=debug,file

As explained earlier there are 2 approaches
First one is to just add this line to your main method:
BasicConfigurator.configure();
Second approach is to add this standard log4j.properties file to your classpath:
While taking second approach you need to make sure you initialize the file properly.
Eg.
Properties props = new Properties();
props.load(new FileInputStream("log4j property file path"));
props.setProperty("log4j.appender.File.File", "Folder where you want to store log files/" + "File Name");
Make sure you create required folder to store log files.

Try to set debug attribut in log4j:configuration node to true.
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">
It prints out information as the configuration file is read and used to configure the log4j environment. You may be got more details to resolve your problem.

Logging API - The Java Logging API facilitates software servicing and maintenance at customer sites by producing log reports suitable for analysis by end users, system administrators, field service engineers, and software development teams. The Logging APIs capture information such as security failures, configuration errors, performance bottlenecks, and/or bugs in the application or platform. The core package includes support for delivering plain text or XML formatted log records to memory, output streams, consoles, files, and sockets. In addition, the logging APIs are capable of interacting with logging services that already exist on the host operating system.
Package java.util.logging « Provides the classes and interfaces of the Java platform's core logging facilities.
Log4j 1.x « log4j is a popular Java-based logging utility. Log4j is an open source project based on the work of many authors. It allows the developer to control which log statements are output to a variety of locations by using Appenders [console, files, DB and email]. It is fully configurable at runtime using external configuration files.
Log4j has three main components:
Loggers - [OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE]
Appenders
Apache Commons Logging: ConsoleAppender, FileAppender, RollingFileAppender, DailyRollingFileAppender, JDBCAppender-Driver, SocketAppender
Log4J Appender for MongoDB: MongoDbAppender - Driver
Layouts - [PatternLayout, EnhancedPatternLayout]
Configuration files can be written in XML or in Java properties (key=value) format.
log4j_External.properties « Java properties (key=value) format
The string between an opening "${" and closing "}" is interpreted as a key. The value of the substituted variable can be defined as a system property or in the configuration file itself.
Set appender specific options. « log4j.appender.appenderName.option=value, For each named appender you can configure its Layout.
log4j.rootLogger=INFO, FILE, FILE_PER_SIZE, FILE_PER_DAY, CONSOLE, MySql
#log.path=./
log.path=E:/Logs
# https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html
# {%-5p - [WARN ,INFO ,ERROR], %5p 0- [ WARN, INFO,ERROR]}
log.patternLayout=org.apache.log4j.PatternLayout
log.pattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n
# System.out | System.err
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.err
log4j.appender.CONSOLE.layout=${log.patternLayout}
log4j.appender.CONSOLE.layout.ConversionPattern=${log.pattern}
# File Appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log.path}/logFile.log
#log4j:ERROR setFile(null,false) call failed. - Defaults setFile(null,true)
#log4j.appender.FILE.Append = false
log4j.appender.FILE.layout=${log.patternLayout}
log4j.appender.FILE.layout.ConversionPattern=${log.pattern}
# BackUP files for every Day.
log4j.appender.FILE_PER_DAY=org.apache.log4j.DailyRollingFileAppender
# [[ Current File ] - logRollingDayFile.log ], { [BackUPs] logRollingDayFile.log_2017-12-10, ... }
log4j.appender.FILE_PER_DAY.File=${log.path}/logRollingDayFile.log
log4j.appender.FILE_PER_DAY.DatePattern='_'yyyy-MM-dd
log4j.appender.FILE_PER_DAY.layout=${log.patternLayout}
log4j.appender.FILE_PER_DAY.layout.ConversionPattern=${log.pattern}
# BackUP files for size rotation with log cleanup.
log4j.appender.FILE_PER_SIZE=org.apache.log4j.RollingFileAppender
# [[ Current File ] - logRollingFile.log ], { [BackUPs] logRollingFile.log.1, logRollingFile.log.2}
log4j.appender.FILE_PER_SIZE.File=${log.path}/logRollingFile.log
log4j.appender.FILE_PER_SIZE.MaxFileSize=100KB
log4j.appender.FILE_PER_SIZE.MaxBackupIndex=2
log4j.appender.FILE_PER_SIZE.layout=${log.patternLayout}
log4j.appender.FILE_PER_SIZE.layout.ConversionPattern=${log.pattern}
# MySql Database - JDBCAppender
log4j.appender.MySql=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.MySql.driver=com.mysql.jdbc.Driver
log4j.appender.MySql.URL=jdbc:mysql://localhost:3306/automationlab
log4j.appender.MySql.user=root
log4j.appender.MySql.password=
log4j.appender.MySql.layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.MySql.layout.ConversionPattern=INSERT INTO `logdata` VALUES ('%p', '%d{yyyy-MM-dd HH:mm:ss}', '%C', '%M', '%L', '%m');
#log4j.appender.MySql.sql=INSERT INTO `logdata` VALUES ('%p', '%d{yyyy-MM-dd HH:mm:ss}', '%C', '%M', '%L', '%m');
# Direct log events[Messages] to MongoDB Collection - MongoDbAppender
log.mongoDB.hostname=loalhost
log.mongoDB.userName=Yash777
log.mongoDB.password=Yash#123
log.mongoDB.DB=MyLogDB
log.mongoDB.Collection=Logs
log4j.appender.MongoDB=org.log4mongo.MongoDbAppender
log4j.appender.MongoDB.hostname=${log.mongoDB.hostname}
log4j.appender.MongoDB.userName=${log.mongoDB.userName}
log4j.appender.MongoDB.password=${log.mongoDB.password}
log4j.appender.MongoDB.port=27017
log4j.appender.MongoDB.databaseName=${log.mongoDB.DB}
log4j.appender.MongoDB.collectionName=${log.mongoDB.Collection}
log4j.appender.MongoDB.writeConcern=FSYNCED
MySQL Table structure for table logdata
CREATE TABLE IF NOT EXISTS `logdata` (
`Logger_Level` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
`DataTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`ClassName` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`MethodName` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`LineNumber` int(10) NOT NULL,
`Message` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
log4j_External.xml « XML log4j:configuration with public DTD file
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration PUBLIC
"-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration debug="false">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<param name="target" value="System.out" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n" />
</layout>
</appender>
<appender name="FILE" class="org.apache.log4j.FileAppender">
<param name="file" value="E:/Logs/logFile.log" />
<param name="append" value="false" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n" />
</layout>
</appender>
<appender name="FILE_PER_SIZE" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="E:/Logs/logRollingFile.log" />
<param name="immediateFlush" value="true"/>
<param name="maxFileSize" value="100KB" />
<param name="maxBackupIndex" value="2"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n" />
</layout>
</appender>
<appender name="FILE_PER_DAY" class="org.apache.log4j.DailyRollingFileAppender">
<param name="file" value="E:/Logs/logRollingDayFile.log" />
<param name="datePattern" value="'_'yyyy-MM-dd" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n"/>
</layout>
</appender>
<root>
<priority value="info" />
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
<appender-ref ref="FILE_PER_SIZE" />
<appender-ref ref="FILE_PER_DAY" />
</root>
</log4j:configuration>
Log4j Configuration from the URL in Java program:
In order to specify a custom configuration with an external file, the used class must implement the Configurator interface.
when default configuration files "log4j.properties", "log4j.xml" are not available
For "log4j.properties" you can fed to the PropertyConfigurator.configure(java.net.URL) method.
For "log4j.xml" DOMConfigurator will be used.
public class LogFiles {
// Define a static logger variable so that it references the Logger instance named "LogFiles".
static final Logger log = Logger.getLogger( LogFiles.class );
#SuppressWarnings("deprecation")
public static void main(String[] args) {
System.out.println("CONFIGURATION_FILE « "+LogManager.DEFAULT_CONFIGURATION_FILE);
System.out.println("DEFAULT_XML_CONFIGURATION_FILE = 'log4j.xml' « Default access modifier");
String fileName = //"";
//"log4j_External.xml";
"log4j_External.properties";
String configurationFile = System.getProperty("user.dir")+"/src/" + fileName;
if( fileName.contains(".xml") ) {
DOMConfigurator.configure( configurationFile );
log.info("Extension *.xml");
} else if ( fileName.contains(".properties") ) {
PropertyConfigurator.configure( configurationFile );
log.info("Extension *.properties");
} else {
DailyRollingFileAppender dailyRollingAppender = new DailyRollingFileAppender();
dailyRollingAppender.setFile("E:/Logs/logRollingDayFile.log");
dailyRollingAppender.setDatePattern("'_'yyyy-MM-dd");
PatternLayout layout = new PatternLayout();
layout.setConversionPattern( "%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS} %C{1}:%12.20M:%L - %m %n" );
dailyRollingAppender.setLayout(layout);
dailyRollingAppender.activateOptions();
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.DEBUG);
rootLogger.addAppender(dailyRollingAppender);
log.info("Configuring from Java Class.");
}
log.info("Console.Message.");
method2();
methodException(0);
}
static void method2() {
log.info("method2 - Console.Message.");
}
static void methodException(int b) {
try {
int a = 10/b;
System.out.println("Result : "+ a);
log.info("Result : "+ a);
} catch (Exception ex) { // ArithmeticException: / by zero
log.error(String.format("\n\tException occurred: %s", stackTraceToString(ex)));
}
}
public static String stackTraceToString(Exception ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
return sw.toString();
}
}

For testing, a quick-dirty way including setting log level:
org.apache.log4j.BasicConfigurator.configure();
org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.WARN);
// set to Level.DEBUG for full, or Level.OFF..

The fix for me was to put "log4j.properties" into the "src" folder.

If we are using apache commons logging wrapper on top of log4j, then we need to have both the jars available in classpath. Also, commons-logging.properties and log4j.properties/xml should be available in classpath.
We can also pass implementation class and log4j.properties name as JAVA_OPTS either using -Dorg.apache.commons.logging.Log=<logging implementation class name> -Dlog4j.configuration=<file:location of log4j.properties/xml file>. Same can be done via setting JAVA_OPTS in case of app/web server.
It will help to externalize properties which can be changed in deployment.

This is an alternative way using .yaml
Logic Structure:
Configuration:
Properties:
Appenders:
Loggers:
Sample:
Configutation:
name: Default
Properties:
Property:
name: log-path
value: "logs"
Appenders:
Console:
name: Console_Appender
target: SYSTEM_OUT
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
File:
name: File_Appender
fileName: ${log-path}/logfile.log
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
Loggers:
Root:
level: debug
AppenderRef:
- ref: Console_Appender
Logger:
- name: <package>.<subpackage>.<subsubpackage>.<...>
level: debug
AppenderRef:
- ref: File_Appender
level: error
Ref: LOG4J 2 CONFIGURATION: USING YAML

Maven solution:
I came across all the same issues as above, and for a maven solution I used 2 dependencies. This configuration is only meant for quick testing if you want a simple project to be using a logger, with a standard configuration. I can imagine you want to make a configuration file later on if you need more information and or finetune your own logging levels.
<properties>
<slf4jVersion>1.7.28</slf4jVersion>
</properties>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4jVersion}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>${slf4jVersion}</version>
</dependency>

I just did this and the issue was fixed.
Followed the below blog
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206875685-How-to-fix-log4j-WARN-console-messages-when-running-an-Application-inside-IntelliJ-Idea
But here he says like below
To fix that just enter the following log4j.resources file into main/resources folder of your project
instead of creating log4j.resources, create log4j.properties. Right Click on Resource in IntelliJ -> New -> Resource Bundle - Just name it as log4j

If you are having this error on Intellij IDEA even after adding the log4j.properties or log4j.xml file on your resources test folder, maybe the Intellij IDEA is not aware yet about the existence of the file.
So, after add the file, right click on the file and choose Recompile log4j.xml.

Related

spring boot logback rolling file append-er not working

I am developing a spring boot application, where I am reading the logback configuration from a YML file which is in Consul . Following are the configuration I have used in the YML file.
logging:
file: ./logs/application.log
pattern:
console: "%d %-5level %logger : %msg%n"
file: "%d %-4relative [%thread] %-5level %logger{35} - %msg%n"
level:
org.springframework.web: ERROR
com.myapp.somepackage: DEBUG
appenders:
logFormat: "%d %-4relative [%thread] %-5level %logger{35} - %msg%n"
currentLogFilename: ./logs/application.log
archivedLogFilenamePattern: ./logs/application-%d{yyyy-MM-dd}-%i.log.gz
archivedFileCount: 7
timeZone: UTC
maxFileSize: 30KB
maxHistory: 30
Now the log files are generated, but the rolling appender is not working, any help on this, I am seraching for something similar like following when we perform rolling appender froma logback.xml file
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- daily rollover. Make sure the path matches the one in the file element or else
the rollover logs are placed in the working directory. -->
<fileNamePattern>./logs/myapp/application_%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>5MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!-- keep 30 days' worth of history -->
<maxHistory>30</maxHistory>
</rollingPolicy>
The same I need to configure from a YML file
After a lot of search what I found is, this is not yet supported in spring boot. The options are only :
# LOGGING
logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions.
logging.file= # Log file name. For instance `myapp.log`
logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG`
logging.path= # Location of the log file. For instance `/var/log`
logging.pattern.console= # Appender pattern for output to the console. Only supported with the default logback setup.
logging.pattern.file= # Appender pattern for output to the file. Only supported with the default logback setup.
logging.pattern.level= # Appender pattern for log level (default %5p). Only supported with the default logback setup.
logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized.
So , dont waste your time on this for now. It will roll after 20MB , but the file name is like ${your_file_name}.log.1 etc. Spring should give support to give the rolling filename pattern to us. And also it is not an archived file.

SpringBoot with LogBack creating LOG_PATH_IS_UNDEFINED folder

I am using SpringBoot with LogBack and using the below configuration in my yml file:
logging:
path: C:/var/log/pincode
The logging.path Spring Environment Variable is transferred to the LOG_PATH Environment variable and the log file is placed at the correct place, but there is also a directory called LOG_PATH_IS_UNDEFINED created in the root directory of my project.
This seems to be caused by the different phase used by SpringBoot to configure LogBack with its Environment variables.
17:29:21,325 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,337 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd}'.
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,343 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:24:07 BRT 2014
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: LOG_PATH_IS_UNDEFINED/catalina.out
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [LOG_PATH_IS_UNDEFINED/catalina.out]
...
17:29:21,358 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
And then after that it start configuring logback again but this time using the path i set:
17:29:21,672 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd}'.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:29:21 BRT 2014
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: C:/var/log/pincode//catalina.out
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [C:/var/log/pincode//catalina.out]
...
17:29:21,685 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
My logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<include resource="org/springframework/boot/logging/logback/basic.xml" />
<property name="FILE_LOG_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } [%t] --- %-40.40logger{39} : %m%n%wex" />
<appender name="serverConsole"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<Append>true</Append>
<File>${LOG_PATH}/catalina.out</File>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/catalina.out.%d{yyyy-MM-dd}
</fileNamePattern>
<maxHistory>15</maxHistory>
</rollingPolicy>
</appender>
<!-- Plain Text Rolling Appender -->
<appender name="server"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<Append>true</Append>
<File>${LOG_PATH}/pincode.log</File>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/pincode.log.%d{yyyy-MM-dd}
</fileNamePattern>
<maxHistory>15</maxHistory>
</rollingPolicy>
</appender>
<!-- Plain Text Rolling Appender -->
<appender name="server-error"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<Append>true</Append>
<File>${LOG_PATH}/pincode-error.log</File>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/pincode-error.log.%d{yyyy-MM-dd}
</fileNamePattern>
<maxHistory>15</maxHistory>
</rollingPolicy>
</appender>
<logger name="com.app" level="INFO">
<appender-ref ref="server" />
<appender-ref ref="server-error" />
</logger>
<root level="INFO">
<appender-ref ref="serverConsole" />
</root>
If I remove my logback.xml file from the project it doesn't create the folder, so somewhere Spring is loading the xml before parsing the yml?
How can I avoid Logback to create this LOG_PATH_IS_UNDEFINED directory?
In your case LOG_PATH is not defined on startup. You should use ${LOG_PATH:-.} instead , See .
But if you define logging.path in your application.properties you will see two log files in . and in ${logging.path} directory.
Spring container set LOG_PATH after Logback initialization... Logback is not supported lazy file creation as far as I know. In this case you should use logback-spring.xml instead logback.xml.
I faced similar issue and its easy to solve it. Basically , concept is that Spring Boot already gives you System property - LOG_PATH for Spring Boot property - logging.path so you define logging.path in your application.properties and simply use LOG_PATH in your logback configuration - logback-spring.xml.
You shouldn't declare logback <property ...> for LOG_PATH , just use it whenever you want.
See at near bottom here
I encountered the same problem.
put an entry in logback.xml
<property resource="application.properties" />
In application.properties
FILE_LOG_PATTERN=###
LOG_FILE=###
when your application starts,the name of the directory created is what you have defined in the properties file.
Might not be your case but if you have bootstrap.properties make sure logging.path is defined there and only there.
if you're on Spring Boot Finchley (2.x), you can define spring.application.name in your application.properties or application.yml file and add the following in your Logback configuration:
<configuration>
<springProperty scope="context" name="springAppName" source="spring.application.name"/>
</configuration>
you will now have ${springAppName} as a variable at your disposal for your log pattern.
Before Spring Boot enviroment is prepared, the Spring Boot main class or the SpringApplication will initialize the loggerfactory, which will detect the default configuration file (logback.groovy, logback.xml, logback-test.xml), but at this time the Spring Boot application is not started yet, which means the variable LOG_PATH is not set. So at first you should alter the name of your logback config file and configure the file name manually in the Spring Boot config as logging.config. By this way the logback will configure a console appender by default instead of creating a file appender, and then when the Spring Boot enviroment is ready it will fire an enviromentready event, which causes a logback reconfig by LoggingApplicationListener. You can find the issue at springboot's page https://github.com/spring-projects/spring-boot/issues/2558
If you upgrade your Spring Boot version into pom.xml, make sure that your replaced
logging.path = your/log/path
by
logging.file.path = your/log/path
into application.properties. That was my case.
I encountered the same problem. I tried to define my own logback.xml and had trouble using the logging.path and logging.file properties defined in my application.properties file. Here is how I resolved (and worked around) the issues.
First, I learned that you cannot define both logging.path and logging.file properties. Since I'm using a RollingFileAppender that will produce multiple files over multiple days, I define logging.file, but use it more like a file prefix.
In application.properties
# Don't add the file type at the end. This will be added in logback.xml
logging.file=logs/my-app-name
In src/main/resources/logback.xml
<configuration>
<property name="FILE_LOG_PATTERN" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>${FILE_LOG_PATTERN}</Pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<Pattern>${FILE_LOG_PATTERN}</Pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>
This seems to work for the most part. I defined my own FILE_LOG_PATTERN in the file, which I think is optional. The interesting part is the fileNamePattern. It correctly translates logging.file from my application.properties file into the variable LOG_FILE. The only real ugliness here is that on startup Logback still complains about the log file being undefined and creates an empty file called LOG_FILE_IS_UNDEFINED_XXX in the current directory. But the actual log file in my property is created and correctly appended to.
Andrew
somewhere Spring is loading the xml before parsing the yml
so just rename logback.xml to your-logback.xml and add logging.config=classpath:your-logback.xml in your application.properties
Do below to create dev/log directory only. Do not add log.path in application.properties
Add log.path=dev/logs in your bootstrap.properties.
Add below line in your logback-spring.xml.
<springProperty scope="context" name="LOG_PATH" source="log.path"/>
<property name="LOG_FILE" value="${LOG_PATH}/app/current"/>
Note
Make sure you include the below line only.
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
Do not use the below line else console logs will never be disabled and spring.log file will be created in temp directory(if you dont not provide logging.path in application.properties). The check the code of below file to know more.
<include resource="org/springframework/boot/logging/logback/base.xml"/>
put an entry in logback:
<property name="DEV_HOME" value="c:/application_logs/ps-web" />
and reference it:
<fileNamePattern>${DEV_HOME}.%d{yyyy-MM-dd}.log</fileNamePattern>
I had the same problem since I configured logging.path and logging.file on application.properties but some logs was produced before Spring Boot LogBack configuration and so they were written into LOG_PATH_IS_UNDEFINED/LOG_FILE_IS_UNDEFINED file and then the logs switched to the right location.
I found 2 possible solutions:
1) Configure logging.path and logging.file in bootstrap.properties since the configuration in bootstrap take place before
or
2) Set logging.path and logging.file as system properties with -Dlogging.path=... -Dlogging.file=... when launching the application
Based on Spring Boot common properties,
add the following into your application.yml
logging:
file:
path: logs/dev
if using application.properties, it should be
logging.file.path = logs/dev
Declare the property LOG_PATH in your logback.xml
<property name="LOG_PATH" value="" />
is where you must specify the directory where the log files are created. If this field is left empty, logback will create a new directory in the program execution. The name of the directory created is LOG_PATH_IS_UNDEFINED
Try adding the following to your POM file
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<filesets>
<fileset>
<directory>${basedir}/catalina.base_IS_UNDEFINED</directory>
<includes>
<include>**/*.log</include>
</includes>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
</plugin>
To call an logback form an external path in a .yml file, it worked for me as:
logging:
config: C:/folder/logback.xml
I suppose you have included an error file.
Please change
<include resource="org/springframework/boot/logging/logback/basic.xml" />
to
<include resource="org/springframework/boot/logging/logback/base.xml"/>
then have a try.
version: 1.5.9
springcloud:
bootstrap.yml
spring:
application:
name: awesome-app
# profile:
# active: dev
logging:
path: /code/awesome-app
spring-logback.xml
${LOG_PATH}/awesome-app.log
springboot:
application.yml
spring:
application:
name: awesome-app
# profile:
# active: dev
logging:
path: /code/awesome-app
spring-logback.xml
${LOG_PATH}/awesome-app.log
custom-log-configuration:https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/htmlsingle/#boot-features-custom-log-configuration
I was also having similar issue. I resolved it by renaming logback-spring.xml to logback-whatever.xml and added below in application.properties:
logging.config=classpath:logback-whatever.xml
Also, this issue comes when we use user defined properties for logging purposes such as:
log.path=logs
log.archive.path=archived
What worked for me:
having logback-spring.xml under resources folder (the same as yamls)
setting the environment variable in the application.yaml
after modifications, do a ./gradlew clean build
Happy new year everybody!
So, I've updated my spring boot to version (2.4.1) and I started getting the LOG_PATH_IS_UNDEFINED error.
I did a bit of research and I'm guessing there is a problem with the mapping of the properties from logging.path to LOG_PATH. (I manually debugged the logger and the properties were being load)
My solution/Patch:
I added a manual mapping to the logback-spring.xml at the very top:
<springProperty scope="context" name="LOG_PATH" source="logging.path"/>
Now it is working for me...

Warning when starting spring tool suite

I am just starting out on trying the spring tool suite v3.4.0 under oracle java 7u40 on Ubuntu Desktop AMD64 13.10 However, when I start the application from the command prompt, I get the following warning:
log4j:WARN No appenders could be found for logger (org.springsource.ide.eclipse.commons.core.templates.TemplateProcessor).
log4j:WARN Please initialize the log4j system properly.
I probably need to configure log4j.properties somewhere, however I am not sure where and how I link the config to STS. Has anyone got a log4j.properties for STS and how do I link it to the STS startup.
I tried the following log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</appenders>
<loggers>
<root level="trace">
<appender-ref ref="Console"/>
</root>
</loggers>
</configuration>
And added the following environment variable:
export JAVA_OPTS=-Dlog4j.configurationFile=~/Log4j/log4j2.xml
However, I still get the same warning when starting STS.
You have a number of options:
Specify the location of the log4j configuration file on the file system. The path in a file: URL must be absolute. On Windows, file: URLs start with either "file:/", or "file:///", and '/' characters replace '\' characters in the path. Your line would be:
export JAVA_OPTS=-Dlog4j.configurationFile=file:/path/to/your/log4j2.xml
Specify the location of the log4j configuration file relative to a classpath entry. If the "/path/to/your/" directory is on the classpath your line would be:
export JAVA_OPTS=-Dlog4j.configurationFile=log4j2.xml
Specify the location of log4J configuration file to be used for all JVMs. Your line would be:
export _JAVA_OPTIONS=-Dlog4j.configurationFile=file:/path/to/your/log4j2.xml
Specify the location of the log4j configuration file on the Java command line for your application. Your line would be:
-Dlog4j.configurationFile=file:/path/to/your/log4j2.xml
In your question, you don't specify what application you are running, but these options will all work.
If you are trying to specify the log4j configuration to use in an application running on a JEE container, e.g. a web application, please refer to the log4j documentation.
I hope this helps you out.
My original assumption and answer were incorrect.
Setting the JVM option -Dlog4j.debug=true revealed that Eclipse ignores the log4j.configurationFile property and looks for either log4j.xml or logj.properties on the classpath.
I do not know how to change the system classpath for Eclipse, so I put the log4j configuration in the JRE's endorsed directory. The steps are:
Put your log4j configuration file in a jar file, say log4jconfig.jar
Put that jar file in the JRE's endorsed directory. On my Windows 7 system, this is "...\JDK1.7.0\jre\lib\endorsed". If the directory does not exist, create it.
The log4j configuration I used is:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="Console" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="ALL" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
</layout>
</appender>
<root>
<level value="all" />
<appender-ref ref="Console" />
</root>
</log4j:configuration>
I hope this helps.

Log SQL queries in project using MyBatis and Spring

In my project i have
<bean id="ABCSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="ABCDataSource" />
<property name="mapperLocations">
<list>
<value>classpath:com/myco/dao/XYZMapper.xml</value>
</list>
</property>
<bean>
and
log4j.logger.java.sql.Connection=debug, stdout, abclog
log4j.logger.java.sql.PreparedStatement=debug, stdout, abclog
log4j.logger.java.sql=debug, stdout, abclog
log4j.logger.org.mybatis=debug, stdout, abclog
log4j.logger.org.apache.ibatis=debug, stdout, abclog
I dont see the SQL queries when i run the applicartion in log
Wanted to know what am i missing
saw this post how to configure log4j for Mybatis to print my SQL
suggesting to change mybatis class configuration but not sure how to do with spring SqlSessionFactoryBean
Quoting from an answer of how to configure logback for Mybatis to print my SQL, I'm not sure if this will work for you in entirety. It provides the Spring config for logging. This approach worked for me.
To log SQL statements for particular mybatis mapper set DEBUG (TRACE
to see query parameters and results) level for logger with fully
qualified mapper name
<logger name="com.mycompany.myapp.mapper.MyMapper" level="DEBUG"/>
You can log all SQL statements from all mappers if they are in the
same package like this
<logger name="com.mycompany.myapp.mapper" level="DEBUG"/>
Give it a go, if the problem is still there. Good luck!
You can add logging for Mybatis via it's mybatis-config.xml.
Add log4j like so:
mybatis-config.xml
<configuration>
<settings>
...
<setting name="logImpl" value="LOG4J"/>
...
</settings>
</configuration>
Then in your log4j.properties, add the class that you'd like to log:
log4j.logger.org.mybatis.example.MyMapper=TRACE
SQL statements are logged at the DEBUG level, so set output to DEBUG:
log4j.logger.org.mybatis.example=DEBUG
For more details, see the documentation.
Another shortcut is to set the debug level of your mybatis mappers to true in your application.properties file:
logging.level.<packageName>.mapper=DEBUG
Example log printed in console or your log file:
2020-03-03 09:41:27.057 DEBUG 10495 --- [io-50006-exec-1] c.f.t.d.m.M.countByExample : ==> Preparing: SELECT count(*) FROM MessageRecivers WHERE ((ReciverId = ? and ReadStats = ? and ReciverMessageFolder <> ?))
2020-03-03 09:41:27.066 DEBUG 10495 --- [io-50006-exec-1] c.f.t.d.m.M.countByExample : ==> Parameters: 58(Long), 0(Short), 1(Short)
2020-03-03 09:41:27.473 DEBUG 10495 --- [io-50006-exec-1] c.f.t.d.m.M.countByExample : <== Total: 1
Test with the simplest way configuration and see in the log. Then customize the output (e.g. the files, levels).
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN"
"log4j.dtd" >
<log4j:configuration>
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p (%c.java:%L).%M - %m%n"/>
</layout>
</appender>
<root>
<priority value="TRACE" />
<appender-ref ref="STDOUT"/>
</root>
</log4j:configuration>
Try to add all the necessary lines to your configuration.
Here is the sample that should work:
#configure root logger
log4j.rootLogger=ERROR, file, stdout
#configure all mybatis mappers logging
log4j.logger.com.myco.dao=ERROR
#configure your mapper logging
log4j.logger.com.myco.dao.XYZMapper=DEBUG
#configure appender
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
Two way to implement:
edit logback.xml:
<logger name="mapperPackageName" level="debug"/>
edit application.properties
logging.level.<mapperPackageName>=DEBUG
the mapperPackageName is the package where the Mapper class is located.

How to truncate log file with filter?

I need some filter to truncate a lot of log information that my Java EE Application writes. I'm using Struts2.
This is my file log4j.properties
# Define the root logger with appender file
log = E:\\Uiip\\ProjectWork\\Workspace
log4j.rootLogger = DEBUG, DEBUG_APPENDER
log4j.logger.OTHER_LOGGER=DEBUG, INFO_APPENDER
log4j.additivity.OTHER_LOGGER = false
#File appender for log debug
log4j.appender.DEBUG_APPENDER=org.apache.log4j.FileAppender
log4j.appender.DEBUG_APPENDER.File=${log}/logDebug.txt
#File Appender for log info
log4j.appender.INFO_APPENDER=org.apache.log4j.FileAppender
log4j.appender.INFO_APPENDER.File=${log}/logInfo.txt
# Define the layout for file appender log debug
log4j.appender.DEBUG_APPENDER.layout=org.apache.log4j.PatternLayout
log4j.appender.DEBUG_APPENDER.layout.conversionPattern=%d [%t] %m%n
# Define the layout for file appender log info
log4j.appender.INFO_APPENDER.layout=org.apache.log4j.PatternLayout
log4j.appender.INFO_APPENDER.append=false
log4j.appender.INFO_APPENDER.layout.ConversionPattern= %d [%t] %m%n
Each time I started my app, for the login only, the logdebug file become about 1MB!
What can I use to filter my Debug logfile?
P.s. the infofile works ok!
You can set the error level to categories, for example:
# This will always be printed (except TRACE level...);
log4j.category.org.apache.struts2=DEBUG
# This will be printed only in INFO or higher
log4j.category.org.springframework.beans.factory.xml=INFO
log4j.category.org.springframework.jdbc.core.StatementCreatorUtils = INFO
# This will be printed only in ERROR or higher
log4j.category.com.opensymphony.xwork2=ERROR
log4j.category.freemarker.beans=ERROR
log4j.category.freemarker.cache=ERROR
Read more on log levels
You cannot do filtering using properties file configuration. Use xml configuration instead. The sample configuration with filters
<appender name="MyFileAppender" class="org.apache.log4j.FileAppender">
<param name="File" value="myfile.log"/>
<param name="Append" value="false"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{HH:mm:ss} [%t] %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.StringMatchFilter">
<param name="StringToMatch" value="MyStringToMatch" />
<param name="AcceptOnMatch" value="true" />
</filter>
<filter class="org.apache.log4j.varia.DenyAllFilter"/>
</appender>

Resources