I want to use log4j for generating the logs.
For this I am using the following code :
package com.idm.Test;
import org.apache.log4j.Logger;
public class log4jExample {
static Logger log = Logger.getLogger(log4jExample.class.getName());
public static void main(String[] args) {
log.info("Hello this is a debug message 1");
log.info("Hello this is a debug message 2");
log.info("Hello this is a debug message 3");
}
}
My log4j properties file is given below :
# Define the root logger with appender file
log=G:\\logs
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}\\log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
I want to generate log file inside
G:\logs\log.out
But the problem is that when I run this. There is no log file is created on this path.
When I already created one file into that location with log.out name and run again it is not showing me the logs inside this file.
I put my log4j.properties file inside com.idm.Test package.
You are using the the Java Util Logger in your code
import java.util.logging.Logger;
this is not the log4j logger. Fix your import and ensure that your configuration file will be found (either put in on the classpath or specifiy the location with the log4j.configuration system property - see here)
Note: OP edited question and uses the right import now...
By the way do not use log4j (1) anymore. It has reached its EOL and is not Java 9 ready.
Go with log4j2 (or other current logging frameworks) instead.
I did same like your code and properity, and log file was created.
In my case, log4j.properties is located in the root of class path.
i.e.)
classes/log4j.properties
classes/com/idm/Test/log4jExample
please, check the location of log4j.properties.
You should put log4j.properties in resource folder (source/main/resource), i think it will work correctly.
In case your project is java project (not maven project) i think you should change your code:
package com.idm.Test;
import org.apache.log4j.Logger;
public class log4jExample {
static Logger log = Logger.getLogger(log4jExample.class.getName());
public static void main(String[] args) {
**PropertyConfigurator.configure("yourPath/log4j.properties");**
log.info("Hello this is a debug message 1");
log.info("Hello this is a debug message 2");
log.info("Hello this is a debug message 3");
}
}
Related
please check the attached image of project structure, let me know if i positioned log4j2.properties right.
also have a look at versions of jars I am using.
I wrote a simple program to print logs on console. in order to achieve this I wrote log4j2.properties file as follows.
Root logger option
log4j.rootLogger=INFO, file
log4j.appender.file= org.apache.logging.log4j.core.appender.ConsoleAppender
log4j.appender.file.Target=System.out
log4j.appender.file.Layout=org.apache.logging.log4j.core.layout.PatternLayout
log4j.appender.file.Layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Main program is as follows.(also shown in image)
package goldensource.track.logs;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.PropertiesUtil;
public class TestLogger {
private Logger logger;
private PropertiesUtil pu;
TestLogger()
{
System.setProperty("log4j.configurationFile","log4j2.properties");
logger = LogManager.getLogger(TestLogger.class);
logger.info("Yes I am there!");
logger.debug("I am debugging!");
logger.warn("giving you a warner!");
}
public static void main(String[] args) {
TestLogger z = new TestLogger();
}}
I have created a reference of PropertiesUtil but anyways I am not using it.
when I am executing this program nothing is shown on console. as I could make out, I am not able to load properties file properly.
suggest me any modifications or alternatives with examples.
Thanks in advance!
Without any feedback on the error you are getting, I can guess that one of the problems is with the file name. You should specify the absolute path to your log4j2.properties file when you are setting the system property:
System.setProperty("log4j.configurationFile","/absolute/path/to/log4j2.properties");
In this way the logger system will know exactly where to find your file.
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" />
I have tested this configuration
# Define the root logger with appender file
log4j.rootLogger = DEBUG, CONSOLE, FILE
# CONSOLE appender
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.conversionPattern=%m%n
log4j.appender.CONSOLE.Threshold=debug
# FILE appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
# Set the name of the file
log4j.appender.FILE.File=/home/user/annotator-log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=info
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
using this simple Main.java
package playground;
import org.apache.log4j.Logger;
public class Main {
private final static Logger LOGGER = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
LOGGER.info("Running main ..");
LOGGER.debug("Reading args:");
for (String arg : args) {
LOGGER.debug(" " + arg);
}
LOGGER.info("All done.");
}
}
and it works. The logging gets printed to the console and the file gets created at /home/user/annotator-log.out
However, if I put the .properties file into my web application I can only see the output in the console but the log file is not getting created.
What could be the reason for this?
Try putting this in your web.xml.
<context-param>
<param-name>log4j-config-location</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</context-param>
Programatic solution:
String log4jPropertiesFilePath = ...;
org.apache.log4j.PropertyConfigurator.configure(log4jPropertiesFilePath);
We use it when we only can know file location at runtime!
I am trying to create multiple logs in Log4j, but I am facing a weird problem. Here's the log4j.properties and the code implementing it.
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILEALL
# Define the file appender
log4j.appender.FILEALL=org.apache.log4j.FileAppender
log4j.appender.FILEALL.File=${logfile.name}
# Define the layout for file appender
log4j.appender.FILEALL.layout=org.apache.log4j.HTMLLayout
#log4j.appender.FILEMAIN=org.apache.log4j.FileAppender
#log4j.appender.FILEMAIN.File=${logfilemain.name}
#log4j.appender.FILEMAIN.layout=org.apache.log4j.HTMLLayout
I have added the statement when running both and removed the original one
log4j.rootLogger = DEBUG, FILEALL , FILEMAIN
And this is the java code:
System.setProperty("logfile.name", savePath1);
// System.setProperty("logfilemain.name", savePath1);
logger = Logger.getLogger(HarishLog.class.getName());
PropertyConfigurator.configure("log4j.properties");
The code works perfectly fine till I make one log, but as soon as I enable the setting for 2nd log in either the properties or the javafile, nothing happens.
Besides I am unable to put a different name at
log4j.appender.FILEALL.File=${logfile.name}
it only works for logfile.name and logfilea.name, It doesn't work for any other name if I change it both in the javacode and the properties folder. Why is this???
Thank you
This works for me:
log4j.rootLogger = DEBUG, FILEALL, FILEMAIN
log4j.appender.FILEALL=org.apache.log4j.FileAppender
log4j.appender.FILEALL.File=${logfile.name}
log4j.appender.FILEALL.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILEMAIN=org.apache.log4j.FileAppender
log4j.appender.FILEMAIN.File=${logfilemain.name}
log4j.appender.FILEMAIN.layout=org.apache.log4j.HTMLLayout
import org.apache.log4j.Logger;
public class LogTest {
public static void main(final String... args) {
System.setProperty("logfile.name", "logall.txt");
System.setProperty("logfilemain.name", "logmain.txt");
Logger logger = Logger.getLogger(LogTest.class.getName());
logger.info("hello");
}
}
If you're still having problems, try adding:
log4j.debug = true
to the beginning of your log4j.properties, and check the output messages.
I want specific messages generated from within the same class to be logged separately. So, how can I create 2 different types of loggers within the same class. Currently, the Properties file looks like
log4j.rootCategory=DEBUG, O
# Stdout
log4j.appender.O=org.apache.log4j.ConsoleAppender
log4j.appender.O.layout=org.apache.log4j.PatternLayout
log4j.appender.O.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
# File
log4j.appender.MESSAGE=org.apache.log4j.RollingFileAppender
log4j.appender.MESSAGE.File=target/logs/messages.log
# Control the maximum log file size
log4j.appender.MESSAGE.MaxFileSize=1000KB
# Archive log files (one backup file here)
log4j.appender.MESSAGE.MaxBackupIndex=100
log4j.appender.MESSAGE.layout=org.apache.log4j.PatternLayout
log4j.appender.MESSAGE.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M (% F:% L) - %m%n
log4j.appender.MESSAGE.
log4j.category.failedMessagesLog=INFO, MESSAGE
I'm using the logging in my code as: –
/** Logger. */
Logger logger = Logger.getLogger(MyClass.class);
Logger msgLogger = Logger.getLogger("MESSAGE");
Upon testing, I get an empty log file (messages.log) created.
Any suggestions??
Create two loggers with different names. You can configure them on a per name basis.
A simple way to do this is to add a suffix to you class name. e.g.
Log log1 = LogFactory.getLog(getClass().getName()+".log1");
Log log2 = LogFactory.getLog(getClass().getName()+".log2");
in your properties file.
log4j.category.mypackage.myclass.log1=INFO, MESSAGE1
log4j.category.mypackage.myclass.log2=INFO, MESSAGE2
log4j.rootCategory=DEBUG, O
log4j.appender.O=org.apache.log4j.ConsoleAppender
log4j.appender.O.layout=org.apache.log4j.PatternLayout
log4j.appender.O.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
log4j.appender.MESSAGE=org.apache.log4j.RollingFileAppender
log4j.appender.MESSAGE.File=target/logs/messages.log
log4j.appender.MESSAGE.MaxFileSize=1000KB
log4j.appender.MESSAGE.MaxBackupIndex=100
log4j.appender.MESSAGE.layout=org.apache.log4j.PatternLayout
log4j.appender.MESSAGE.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M
log4j.appender.**MESSAGE2**=org.apache.log4j.RollingFileAppender
log4j.appender.**MESSAGE2**.File=target/logs/**messages2**.log
log4j.appender.**MESSAGE2**.MaxFileSize=1000KB
log4j.appender.**MESSAGE2**.MaxBackupIndex=100
log4j.appender.**MESSAGE2**.layout=org.apache.log4j.PatternLayout
log4j.appender.**MESSAGE2**.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M
log4j.category.failedMessagesLog=INFO, MESSAGE , **MESSAGE2**
"failedMessagesLog" is the java file to which appender (INFO,MESSAGE, MESSAGE1) is applied.
I have just reused existing RollingFileAppender. you can use any other appender ( like fileAppender).
You should use the right Class name Logger logger = Logger.getLogger(MyClass.class)
should be changed to private static final Logger log = Logger.getLogger( **failedMessagesLog.class** );
Make sure you are using log4j's logging ie
import **org.apache.log4j.Logger**;