Where is my Log4J level being set? - java

The following is my Log4J code :
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Level;
public class HelloWorldLog4J {
private static final Logger logger = LogManager.getLogger("HelloWorld");
//private static Logger logger = Logger.getLogger(HelloWorldLog4J.class);
public static void main(String[] args) {
System.out.println("pre_loggerDOTinfo");
System.out.println();
//logger.setLevel(Level.INFO); //used to be..
logger.info("Hello, this is an INFO message");
logger.warn("Hello, this is an WARN message");
logger.fatal("Hello, this is an FATAL message");
logger.fatal("Hello, this is an FATAL message ALSO, #2");
logger.fatal("Hello, this is an FATAL message ALSO, #3");
logger.fatal("Hello, this is an FATAL message ALSO, #4");
logger.debug("Hello, this is an FATAL message");
logger.info("Hello, this is an INFO message");
logger.info("Hello, this is an INFO message");
System.out.println();
System.out.println("post_loggerDOTinfo");
}
}
This works when I run it, and outputs the following :
pre_loggerDOTinfo
12:21:20.761 [main] FATAL HelloWorld - Hello, this is an FATAL
message 12:21:20.763 [main] FATAL HelloWorld - Hello, this is an FATAL
message ALSO, #2
12:21:20.764 [main] FATAL HelloWorld - Hello, this is an FATAL
message ALSO, #3
12:21:20.765 [main] FATAL HelloWorld - Hello, this is an FATAL
message ALSO, #4
11
post_loggerDOTinfo
This is fine , but I want it to output all of the logging messages, not just the FATAL ones.
So what I tried is to create a log4j.properties file in the same directory as the Java file. It is here :
log4j.rootLogger=DEBUG,console,file
log4j.appender.console=DEBUG,org.apache.log4j.ConsoleAppender
log4j.appender.file=INFO,org.apache.log4j.RollingFileAppender
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{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=log4j.log
log4j.appender.FILE.MaxFileSize=512KB
log4j.appender.FILE.MaxBackupIndex=3
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n
But when I re-run the HelloWorldLog4J class, I get the same exact thing (as if it's finding a properties file elsewhere ).
I think that I need to set the log4j properties file within my HelloWorldLog4J class? I did try this , using the line :
logger.setLevel(Level.INFO);
However, this doesn't work - and I get this error :
HelloWorldLog4J.java:20: error: cannot find symbol
logger.setLevel(Level.INFO); //used to be..
^
symbol: method setLevel(Level)
location: variable logger of type Logger
1 error
C:\Users\Adel\JavaCoding>
any tips appreciated thanks

Maybe you are importing any library with a custom log4.properties file, or your properties file is not visible on the classpath
See here for a discussion on how to setup
https://logging.apache.org/log4j/1.2/manual.html#defaultInit
You could try to set the log4j.configuration property when starting your class.
-Dlog4j.configuration="PATH_TO_YOUR_FILE"
And see if this is now picked up

Related

Log4j not printing lower levels than WARN and creating no log files

I have the following log4j2.properties file
# Root logger option
log4j.rootLogger=DEBUG, stdout
## Direct log messages to file
log4j.appender.fileout=org.apache.log4j.FileAppender
log4j.appender.fileout.File=/logs/bbt_${current.date}.log
log4j.appender.fileout.ImmediateFlush=true
log4j.appender.fileout.Threshold=info
log4j.appender.fileout.Append=false
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.conversionPattern=%5p | %d | %m%n
# Direct log messages to terminal
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=%5p | %d | %m %n
and the following temporary test class
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Temp {
private static Logger log = LogManager.getLogger();
public static void main(String[] args) {
log.error("error");
log.debug("debug");
log.info("info");
log.fatal("fatal");
log.trace("trace");
log.warn("warn");
}
}
However, when I run the test class I get the following output:
11:32:19.295 [main] ERROR Temp - error
11:32:19.298 [main] FATAL Temp - fatal
Additionally, no /logs/ folder or log files are created. I thought the issue with the log levels might be caused by the fact that I'm setting a treshold in the first block (for the file), but commenting out this block makes no difference. Does anyone have an idea what could be the cause here?
It looks to me like you've used a properties file from Log4J version 1, but are trying to use Log4J version 2.
This version 2 properties file, named as log4j2.properties on the classpath, worked for me:
name=PropertiesConfig
rootLogger.level=debug
rootLogger.appenderRefs=stdout, file
rootLogger.appenderRef.stdout.ref=StandardOutput
rootLogger.appenderRef.file.ref=LogFile
appenders=console, file
## Direct log messages to file
appender.file.type=File
appender.file.name=LogFile
appender.file.fileName=logs/bbt_${current.date}.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=%5p | %d | %m%n
# Direct log messages to terminal
appender.console.type=Console
appender.console.name=StandardOutput
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=%5p | %d | %m %n

Log4j Could Not Read Configuration File SELENIUM JAVA

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" />

Why does log4j create the logfile in my Java application but not in my web application?

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!

Logging to 2 log files using 2 loggers is duplicating the logs (using log4j)

I am trying to create 2 log files using log4j using this configuration:
log4j.rootLogger=debug,stdout,logfile
#debug info warn error fatal
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache=FATAL,logfile
# ConsoleAppender properties
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.Threshold=debug
log4j.appender.stdout.layout.ConversionPattern=%d %5p %c{1}:%L - %m%n
#%-5p [%t]: %m%n
# LogFileAppender properties
log4j.appender.logfile=com.xx.util.SizeRollingFileAppender
log4j.appender.logfile.File=log.log
log4j.appender.logfile.MaxFileSize=50240KB
log4j.appender.logfile.BackupsDirectory=log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %5p %c{1}:%L - %m%n
log4j.appedner.logfile.Threshold=error
# Log1FileAppender properties
log4j.appender.log1=com.xx.util.SizeRollingFileAppender
log4j.appender.log1.File=log1.log
log4j.appender.log1.MaxFileSize=5120KB
log4j.appender.log1.BackupsDirectory=log
log4j.appender.log1.layout=org.apache.log4j.PatternLayout
log4j.appender.log1.layout.ConversionPattern=%d %5p %c{1} :%L - %m%n
(the xx is for the project that I am working on) -
And here it is the Java Code:
public class TestLog4j {
/**
* #param args
*/
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(TestLog4j.class);
private static org.apache.log4j.Logger log1= org.apache.log4j.Logger.getLogger("log1");
public static void main(String[] args) {
// TODO Auto-generated method stub
org.apache.log4j.PropertyConfigurator.configure("src/com/test/log4j.properties");
log.error("Error Test Log");
log1.info("Test Log1");
}
}
My problem is that I want to write two different files, one for log and one for log1. What I am getting with this code is only one file being created with both logs in the same file.
What I am doing wrong?
Short answer:
Add:
log4j.logger.log1=<yourLogLevel>,log1
to your log4j.properties.
NOTE:
Every enabled log-request to log1 (log-level >= yourLogLevel) will go to both stdout and logfile unless you turn off appender-additivity!

how to write to a text file using to log4j?

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

Categories