Log4j - Print test case name in log file - java

I have a java project which uses log4j as a logger. The requirement is to have the test case name printed in the log file.
There are multiple tests in one class And the project supports parallel execution as well. A logger instance is created for each test.
I used system.Setproprty to associate my current logger instance with a the test case name. Following is my log4j.properties file :-
log4j.appender.logFileAppender.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss} [%t] ${testCaseName} %5p (%F:%L) - %m%n
log4j.appender.logFileAppender.Append=false
log4j.appender.logFileAppender.file=./log/UITest.log
And the runtime variable ${testCaseName} is set while creating a new instance of logger file as follows :-
public Logger log;
public synchronized Logger initializeLogger(String testName)
{
log = LoggerFactory.getLogger(testName);
System.setProperty("testCaseName", testName);
PropertyConfigurator.configure(log4jPropertiesFilePath);
return log;
}
The above looger instance creation method is called in a #BeforeMethod.
Currently the logger file is printing the test name of the last test in a class (In non-parallel ans parallel execution mode)
Kindly help me identify the issue due to which multiple test cases are not having their testcase name printed in the log file.

try adding this to your test
#Rule
public TestName testName = new TestName();
#Before
public void printTestName() {
System.out.println("Running ==> " + testName.getMethodName());
}

What you can do is to set up a thead context variable, and use this variable name in the log4j configuration files.
In the java method level code, save the testName into the thread context "testCaseName".
import org.apache.logging.log4j.ThreadContext;
ThreadContext.put("testCaseName", testName);
From the log4j2 config, print the thread context variable by adding this line:
${ctx:testCaseName}]
It works for me, good luck.

Related

log4j ConsoleAppender printing to console twice even after setting Additivity to false

I have log4j appenders that print outputs to the console once when running the program in intellIj
but twice when running the program via executable .jar.
The actual logs that get written to the log file only appear once which is correct.
I define my logger/appenders programmatically in this code block
and after everything is done I call
rootLogger.setAdditivity(false);
but for some reason my classes still output twice to cmdline console when running as a .jar. I call loggers in each class by defining a log variable at the top like so:
public class SomeClass {
static Logger log = Logger.getLogger(SomeClass .class);
and this log variable is used everywhere in the "SomeClass" class.
I've tried setting additivity to false for all the package loggers as well before and after I set their levels...
Logger.getLogger("com.company").setAdditivity(false);
Logger.getLogger("com.company.project.database.Admin").setAdditivity(false);
...
but when I run the code that way it complains it cannot find the appenders for the class that I'm defining all the log4j stuff in, and nothing gets written to output/log.
I think you are on the right track with additivity, however additivity is a property of a child, telling log4j not to use the parents:
https://logging.apache.org/log4net/release/sdk/html/P_log4net_Repository_Hierarchy_Logger_Additivity.htm
You have set additivity to false for the ultimate parent logger, that will never do anything as root will not be a child of anything.
Try setting the additivity to false of each package logger and hopefully that will solve the issue.

How to use custom log4j.properties file for private logging?

I need to periodically append text messages to a text file and I'm wanting to piggyback on log4j to make life easy. So I've created a "mylog.properties" file with a DailyRollingFileAppender -- nothing unusual -- and I've put that file in my src/java/resources directory. So now I'm ready to create a logger from this file and start logging with it, something like this:
class MyClass {
private static final Logger myLog = getLoggerConfiguredFromPropertiesFile("mylog.properties");
public void logSomething(String message) {
myLog.info(message);
}
}
So what would be the logic for getLoggerConfiguredFromPropertiesFile?
Thanks,
Alvaro
Doing:
private static final Logger myLog = Logger.getLogger(MyClass.class)
should get the job done. log4j automatically looks for the closest log4j.properties to the class, and if you only have one in the project, it's that one. Also, call your file log4j.properties, not mylog.properties.
I came up with a workaround where I'm using the regular logger:
private static final Logger myLog = LoggerFactory.getLogger(MyClass.class);
And in the log4j.properties, I configure a custom DailyRollingFileAppender that works just for my class, as explained here.

How do I programmatically create a folder that is to hold a final static log file, in Java

I have a final static logger object, this is created when the main method is first executed. If the log file is not there it is created and then appended to (using the log4j API, appender). However I want to check that the machine that the application is run on has the directory created that the application is due to save into.
The problem is that this folder check/creation needs to happen before the log is created and the log is created on class instantiation. I s there a standard way to deal with this issue, I want to avoid re-placing all the logging statements so keeping the logger static is preferable?
You can use a static initializer to achieve this:
public class Foo {
static {
//check the directory
//initialize the logger
}
}
This static initalizer will run when the class is loaded. So there you can check if the directory exists before you actually create the logger.

Two logs for one class

I'm working on jdk 1.6 and I have a class that needs to log to 2 different log files using log4j. I have read many other answers, but I can't get mine to work the way I want it. This is my log4j properties.
log4j.debug=false
log4j.rootLogger=ERROR, appLog
log4j.logger.com.my.apps.idm.transactionalemail=DEBUG, appLog, infoLog
log4j.appender.appLog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.appLog.File=/opt/apps/logs/${ni.cluster}/TransactionalEmail/1.0/TransactionalEmail.log
log4j.appender.appLog.DatePattern='.'yyyy-MM-dd
log4j.appender.appLog.layout=org.apache.log4j.PatternLayout
log4j.appender.appLog.layout.ConversionPattern=DATE: %d{DATE}%nPRIORITY: %p%nCATEGORY: %c%nTHREAD: %t%nNDC: %x%nMESSAGE:%m%n%n
log4j.appender.infoLog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.infoLog.File=/opt/apps/logs/${ni.cluster}/TransactionalEmail/1.0/Info.log
log4j.appender.infoLog.DatePattern='.'yyyy-MM-dd
log4j.appender.infoLog.layout=org.apache.log4j.PatternLayout
log4j.appender.infoLog.layout.ConversionPattern=DATE: %d{DATE}%nPRIORITY: %p%nCATEGORY: %c%nTHREAD: %t%nNDC: %x%nMESSAGE:%m%n%n
And the way I want this to work is like this
public class MyClass{
private static final LOG = Logger.getLogger("appLog");
private static final INFO_LOG = Logger.getLogger("infoLog");
public void myMethod(){
INFO_LOG.debug("This is info");
LOG.debug("This is debug");
}
}
What happens when I run my app is that the Info.log has the same information as TransactionalEmail.log, and also, the line "This is a test" doesn't show up in either of the log files.
What am I doing wrong?
I would recommend against using multiple logger instances for classes. Utilize log4j's configuration to handle logging events as they are generated. You may want to look at the Routing File Appender to decide how log events are handled. From the link
The RoutingAppender evaluates LogEvents and then routes them to a subordinate Appender. The target Appender may be an appender previously configured and may be referenced by its name or the Appender can be dynamically created as needed. The RoutingAppender should be configured after any Appenders it references to allow it to shut down properly.

How to see the log information after writing up my own java main class

I am using a package with many java classes where a lot of org.apache.commons.logging.Log objects are defined. Now I write my own Java main class using these classes; how can I turn on the log information?
I do have log4j.properties file ready. But I am not sure what needs to be included in the java main class in order for this to be effective.
Thank you.
Edit
My log4j.properties file has the following content:
log4j.rootLogger = DEBUG,sysout
log4j.appender.sysout=org.apache.log4j.ConsoleAppender
log4j.appender.sysout.layout=org.apache.log4j.PatternLayout
The package classes use the logger like the following:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
...
public class AClass {
private static final Log log = LogFactory.getLog(AClass.class);
log.debug("Some info ");
...
I am asking what I need to do in my main class in order to get logging information printed out in stdout.
You don't do it in the Java main class, although it might be possible. You need to modify the log4j.properties.
There is a root appender that should already appear in the property file. Set the level to DEBUG and you should see every log message. I recommend defining a fileappender first though. That way you can use your favorite text editor to browse the log messages.
You should define the conversion pattern for the PatternLayout of your appender.
For example:
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
Try adding the code below to your main class
import org.apache.log4j.BasicConfigurator;
In main():
BasicConfigurator.configure();
This will use a simple configuration which should output all log messages to the console. Accourding to the Apache logging manual, you can send in the name of a config file as a parmeter like so:
import com.foo.Bar;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class MyApp {
static Logger logger = Logger.getLogger(MyApp.class.getName());
public static void main(String[] args) {
// BasicConfigurator replaced with PropertyConfigurator.
PropertyConfigurator.configure(args[0]);
logger.info("Entering application.");
Bar bar = new Bar();
bar.doIt();
logger.info("Exiting application.");
}
}
I'm assuming the logger jar is in the classpath. I don't know about the apache logging framework but Log4J would send a message to the console (or stderr) about not finding the config file, and it could be easily overlooked depending on what else is sent to stdout. Also, (again for log4j) the directory the property file was in had to be in the CLASSPATH as well.
It occurs to me to double check the expected name of the logfile. Log4J uses log4j.properties but is that what the Apache framework expects? Either way, you can declare the name of the config file when the logger is instantiated. Not sure what the methodname is though.

Categories