I am new configuring log4j for a project, I have used it several times, but it´s the first time i have to configure it.
I am configuring my Log4j, I have imported the log4j-1.2.17.jar library, and I have created a properties that look like this:
log4j.appender.consola = org.apache.log4j.ConsoleAppender
log4j.appender.consola.threshold = INFO
log4j.appender.consola.target = System.out
log4j.appender.consola.layout = org.apache.log4j.EnhancedPatternLayout
log4j.appender.consola.layout.ConversionPattern = %d{dd MMM yyyy - HH:mm:ss} [%-5p] %c{2} - %m%n
log4j.appender.archivo = org.apache.log4j.FileAppender
log4j.appender.archivo.file = archivo.log
log4j.appender.archivo.layout = org.apache.log4j.PatternLayout
log4j.appender.archivo.layout.ConversionPattern = %d [%-5p] %c{2} - %m%n
log4j.rootLogger=TRACE, consola
log4j.logger.com.javatutoriales.log4j.configuracion=WARN, archivo
This properties file called log4j.properties is created in the default package of the project.
When I used this configuration in a class, it returns me the console log properly. I used the following code In a class:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PruebaLog {
/** * Logger. */
private static final Logger logger = LoggerFactory.getLogger(PruebaLog.class);
public static void main (String args[]){
logger.trace("mensaje de trace");
logger.debug("mensaje de debug");
logger.info("mensaje de info");
logger.warn("mensaje de warn");
logger.error("mensaje de error");
}
}
The problem is that this class returns me the console out, but doesn´t create the file archivo.log in the path of my project.
Anybody know the reason of why it doesn´t create this log file???
Or anybody could help me with the configuration of this file in order to have a log of the diferent classes of my project in a log file???
You are not using the file appender as you have set the console appender for the root logger:
log4j.rootLogger=TRACE, consola
You need this instead to use the file appender:
log4j.rootLogger=INFO, archivo
Learn more about the appenders and different log4j properties from the official document:
http://logging.apache.org/log4j/1.2/manual.html
in you properties, you need to add rootLogger file
log4j.rootLogger=INFO, archivo
For more details you can refer to log4j.properties config
Related
I created a custom appender and it's not getting called when I run my test. Here's what the properties look like:
name=config
appenders=console, myCustomAppender
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
#appender.console.layout.pattern =%d{HH:mm:ss} [%t] %c{1} [%-5level] - %msg%n
appender.console.layout.pattern=%d{dd-MM-yyyy HH:mm:ss} [%-5p] (%F:%L) - %m%n
appender.myCustomAppender = com.myCompany.logging.log4j.WindowsEventLogAppender
appender.myCustomAppender.name = WindowsEventLogAppender
appender.myCustomAppender.type = WindowsEventLogAppender
rootLogger.level=info
rootLogger.appenderRefs=stdout, myCustomAppender
rootLogger.appenderRef.stdout.ref=STDOUT
My appender is called a WindowsEventLogAppender. Any idea what's wrong with my properties file? I see the console test messages but none of the messages from my appender. Right now I'm just doing a System.out.println in my custom appender to verify it's getting called.
BTW, I've found lot's of XML examples out there for log4j2 configurations with custom appenders but none for using a properties file for configuration.
Thanks,
-Mike
I might be quite late here, but I think my answer can help other people looking for answers. Please accept this as an answer if this is correct!
If you have created a custom appender having annotation like this:
#Plugin(name = "MyCustomAppender", category = "Core",
elementType = "appender", printObject = true)
public final class MyCustomAppenderImpl extends AbstractAppender {
// other code for the plugin....
}
The log4j2 manual about Configuring Appenders states that:
"An appender is configured either using the specific appender plugin's name or with an appender element and the type attribute containing the appender plugin's name"
Meaning the type for appender should be Appender Plugin's Name attribute value.
Which in above case is MyCustomAppender (appender.identifierName.type=MyCustomAppender)
So, the Properties file configuration for this to work should be:
(Note : I have added a stdout(console) appender just to show
relevance/similarity of usage with OOTB appenders, and 2 example
usages with RootLogger and a custom logger)
# this packages attribute is important, please put comma seperated package(s) to the
# plugin(s) you have created
packages = com.package.to.your.plugin
# Example: Declare and Define OOTB Console appender, which sends log events to stdout
appender.console.name = stdout
appender.console.type = Console
# Declare and define the custom appender like this
# Note that the "abc" in "appender.abc.type" can be anything
# and the value for "appender.abc.type" should be the same as
# "Name" attribute value given in custom appender plugin which is "MyCustomAppender"
appender.abc.name=arbitrary_name
appender.abc.type=MyCustomAppender
rootLogger.appenderRef.stdout.ref = stdout
rootLogger.appenderRef.abc.ref = arbitrary_name
logger.loggeridentifier.name = com.test.SomeClass
logger.loggeridentifier.appenderRef.stdout.ref = stdout
logger.loggeridentifier.appenderRef.abc.ref = arbitrary_name
# Also note that the value of appenderRef should be the same name given to your
# appender in properties file, which in this case is "arbitrary_name" (as given above)
Try adding the packages property.
Like: packages = com.myCompany
You haven't included the package info
try the below configuration.
name=config
appenders=console, myCustomAppender
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
#appender.console.layout.pattern =%d{HH:mm:ss} [%t] %c{1} [%-5level] - %msg%n
appender.console.layout.pattern=%d{dd-MM-yyyy HH:mm:ss} [%-5p] (%F:%L) - %m%n
appender.myCustomAppender = com.myCompany.logging.log4j.WindowsEventLogAppender
appender.myCustomAppender.name = WindowsEventLogAppender
appender.myCustomAppender.type = WindowsEventLogAppender
rootLogger.level=info
rootLogger.appenderRefs=stdout, myCustomAppender
rootLogger.appenderRef.stdout.ref=STDOUT
rootLogger.com.mycompany.example=INFO,STDOUT
How do I get log4j to read up a properties file.
I'm writing a Java for testing with selenium which I want to use log4j. As i encounter an error of Log4j could not read configuration file [ERROR] Ignoring configuration file . Kindly advise , Thanks you . In my main method if have this:
static Logger log = Logger.getLogger(Testing.class);
Log4j.properties:
log4j.rootCategory=DEBUG, R
# File
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=D:/log4j.log
# Control the maximum log file size
log4j.appender.R.MaxFileSize=100KB
# Archive log files (one backup file here)
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
My Testcase :
#Test //Tested Login
public void TestLogin_Success() throws Exception {
try{
//PropertyConfigurator.configure("log4j.properties");
driver = new FirefoxDriver();
LoginBuilder.Execute(driver);
log.info("TEST A TEST");
driver.quit();
}catch (Exception e){
//Log.error(e.getMessage());
throw (e);
}
}
You can put the log4j.properties file under the resources folder corresponding to the java folder of your class file.
Also to configure it using configurator you can use the following code :
import org.apache.log4j.PropertyConfigurator;
....your base class
....inside the main/setup method
PropertyConfigurator.configure(Testing.class.getClassLoader().getResource("log4j.properties"));
To make sure if the logger is working or not, you can try and log the same details to the console window and see the differences. Just add these changes and observe :
log4j.rootCategory=DEBUG, console, R
log4j.appender.console =org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p -> %m %n
Or in your case ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
Your log4j.properties expected to be in class path. You also can set it via system property
log4j.configuration
. Below is example for ant target
<sysproperty key="log4j.configuration" value="file:///${lib.dir}/log4j.properties" />
This might be a very easy question for some, but personally I find Log4j config to be nightmarishly difficult and that learning to perform brain surgery might be less challenging.
I am trying to lave multiple loggers logging into different files.
Here is what I have in my log4j.properties file:
# Root logger option
log4j.rootLogger=INFO, file, admin
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/home/nick/logging/file.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{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n
log4j.appender.admin=org.apache.log4j.RollingFileAppender
log4j.appender.admin.File=/home/nick/logging/admin.log
log4j.appender.admin.MaxFileSize=1MB
log4j.appender.admin.MaxBackupIndex=1
log4j.appender.admin.layout=org.apache.log4j.PatternLayout
log4j.appender.admin.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n
And here is my (very simple) Java app used to test the config:
public static void main(String[] args) throws Exception {
Properties resource = new Properties();
InputStream in = new FileInputStream("/home/nick/logging/log4j.properties");
resource.load(in);
PropertyConfigurator.configure(resource);
Logger admin = Logger.getLogger("admin");
Logger file = Logger.getLogger("file");
admin.info("hello admin");
file.info("hello file");
}
I have 2 problems:
One problem I always get an exception in the line PropertyConfigurator.configure(resource);:
java.io.FileNotFoundException: /home/nick/logging (Is a directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:136)
at org.apache.log4j.FileAppender.setFile(FileAppender.java:289)
at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:167)
at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:163)
at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:256)
The 2nd problem is that both messages are written to both logs. Here is the actual result:
File admin:log:
2014-04-27 11:55:30 INFO admin - hello admin
2014-04-27 11:55:30 INFO file - hello file
File file.log:
2014-04-27 11:55:30 INFO admin - hello admin
2014-04-27 11:55:30 INFO file - hello file
Here is the required result:
File admin:log:
2014-04-27 11:55:30 INFO admin - hello admin
File file.log:
2014-04-27 11:55:30 INFO file - hello file
What is causing the exception, and how can I achieve the required result?
Log4J makes a distinction between loggers, which are responsible for generating log messages, and appenders, which are responsible for sending those messages somewhere (a file, the console, a database, etc.). Loggers form a hierarchy, the root logger is the parent of the logger named admin, which is the parent of admin.component1, etc., and you can attach appenders to any logger in the hierarchy. By default a logger will send messages to all appenders that are attached directly to it, or to any of its ancestors in the hierarchy (this is why loggers are conventionally named like Java classes, e.g. you can control logging for com.example.Class1 and com.example.subpkg.AnotherClass by configuring the com.example logger).
Loggers and appenders form separate namespaces and this is the source of your confusion - the logger named admin and the appender named admin are two separate entities.
The configuration you have given in the question defines one logger (the root logger) which sends all the messages it generates to two separate appenders, one for each of the two files. Your code then requests two different loggers and generates one log message with each logger. Both these loggers inherit the appender configuration from the root logger, so they both send their messages to both of the configured appenders.
Instead of attaching the two appenders to the root logger, you should attach the file appender to the file logger and the admin appender to the admin logger:
log4j.rootLogger=INFO
log4j.logger.file=INFO, file
log4j.logger.admin=INFO, admin
This way the file logger will send messages only to file.log, the admin logger only to admin.log, and all messages from other loggers will be silently discarded, as there are no appenders attached to the root.
The additivity flag is the exception to this rule - setting a logger's additivity to false essentially disconnects the arrow from a logger up to its parent, so messages generated by that logger (or flowing into it from one of its children) will not go any further up the tree, they will only go to appenders attached directly to the logger in question.
To answer my own question, this is what I needed:
log4j.logger.file=DEBUG, fileAppender
log4j.logger.admin=DEBUG, adminAppender
log4j.additivity.file=false
log4j.additivity.admin=false
log4j.appender.fileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.fileAppender.File=/home/nick/logging/file.log
log4j.appender.fileAppender.MaxFileSize=1MB
log4j.appender.fileAppender.MaxBackupIndex=1
log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n
log4j.appender.adminAppender=org.apache.log4j.RollingFileAppender
log4j.appender.adminAppender.File=/home/nick/logging/admin.log
log4j.appender.adminAppender.MaxFileSize=1MB
log4j.appender.adminAppender.MaxBackupIndex=1
log4j.appender.adminAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.adminAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n
You don't need to load the properties file. Just place it inside the src folder that will automatically added in class path.
Sample code:
public static void main(String[] args) throws Exception {
Logger admin = Logger.getLogger("admin");
Logger file = Logger.getLogger("file");
admin.info("hello admin");
file.info("hello file");
}
First: log4j recommands to use xml format file for properties.
Second: its better to load the properties file in the classloader.
Third: there is inheritance in logger, but you can cut it with additivity property see log4j.properties file - multiple loggers in same class
I am adding logging to a java web project I am working on. I have run into an error that I am unable to figure out.
The error I am getting from tomcat is:
log4j:ERROR Could not read configuration file [log4j.properties].
java.io.FileNotFoundException: log4j.properties (No such file or directory)
I have this simple method in my class:
#RemotingInclude
public UserAccount save(UserAccount dataObject)
{
PropertyConfigurator.configure("log4j.properties");
logger.debug(dataObject.toString());
return dao.save(dataObject);
}
When I look in my webapps//WEB-INF/class folder I do see my log4j.properties file. When I deploy to my tomcat server and restart tomcat, I do see my admin.log file created, but nothing is written to it. Even after hitting the method above. Any help with this is greatly appreciated.
This is the current contents of my log4j.properties file:
log4j.appender.AdminFileAppender=org.apache.log4j.FileAppender
log4j.appender.AdminFileAppender.File=admin.log
log4j.appender.AdminFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.AdminFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n.
log4j.appender.ReportFileAppender=org.apache.log4j.FileAppender
log4j.appender.ReportFileAppender.File=report.log
log4j.appender.ReportFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.ReportFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n
log4j.logger.com.rottmanj.services=WARN,AdminFileAppender
That approach of bootstraping the Log4j is wrong. This is usually the way that is implemented:
import org.apache.log4j.Logger;
public class MyService {
public UserAccount save(UserAccount dataObject) {
logger.debug(dataObject.toString());
return dao.save(dataObject);
}
private static Logger logger = Logger.getLogger(MyService.class);
}
This way Log4j will automatically lookup for the log4j.properties in the root of the classpath.
I'm wondering how to convert the following code to output those lines into a text file, and not to standard output:
import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
The properties file is :
log4j.rootLogger=DEBUG, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%m%n
Thanks.
Change the ConsoleAppender to a FileAppender.
I find the org.apache.log4j.RollingFileAppender
to be useful.
If you use this,
you must add a property for the fileName and
may want to set the maxFileSize as well.
Here is an example (put these in the log4j.properties file):
log4j.appender.NotConsole=org.apache.log4j.RollingFileAppender
log4j.appender.NotConsole.fileName=/some/path/to/a/fileName.log
log4j.appender.NotConsole.maxFileSize=20MB
There are other appenders.
DailyRollingFileAppender rolls based on time.
FileAppender does not roll.
If you use the RollingFileAppender,
you will need to guess as to a good value for maxFileSize and
then address the size at a future date if it is causing issues.
Shortly use FileAppender instead of ConsoleAppender.
Here is a simple example of configuration. It additionally configures the layout. You can omit it for the first approach.
log4j.appender.F=org.apache.log4j.FileAppender
log4j.appender.F.File=mylog.log
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%d{MM-dd#HH:mm:ss} %-5p (%13F:%L) %3x - %m%n
The following would be helpful:
Class containing main method
package abc;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class ClassOne {
static Logger logger = Logger.getLogger(ClassOne.class);
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.info"); //log4j.info file should be in the class path(same location as ClassOne.class)
logger.info("Program started.... "); //Whenever you want to write something to the log text file use logger.info("Log Message")
}
}
log4j.info file
log4j.rootLogger=INFO, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender // Replacing ConsoleAppender with FileAppender gives text file logging
# Set the name of the file
log4j.appender.FILE.File=src/abc/log.out //Here you can specify either absolute or relative path
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d %m%n
following configuration should aslo work
direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.FileAppender
log4j.appender.stdout.fileName=error.log
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p
%c{1}:%L - %m%n
in log4j.properties
# Define the root logger with file appender
log4j.logger.App = DEBUG ,CA
#set file text
log4j.appender.CA = org.apache.log4j.RollingFileAppender
log4j.appender.CA.File = D:\\database.log
log4j.appender.CA.maxFileSize = 20MB
log4j.appender.CA.MaxBackupIndex=10
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n