configure log4j to log to custom file at runtime - java

Can anyone please guide me as to how I can configure log4j to log to a specific file that I specify at run-time.The name and path of the log file are generated at run-time and the application must log to that particular file.
Generally file appender entries in the log4j.properties file points to the log file that will be used by the application.However in this case I would like to read the log file path from the command line and log to that particular file.
How can I achieve this ?

You can also do this from the log4j.properties file. Using the sample file below I have added the system property ${logfile.name}:
# logfile is set to be a RollingFileAppender
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${logfile.name}
log4j.appender.logfile.MaxFileSize=10MB
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=[%-5p]%d{yyyyMMdd#HH\:mm\:ss,SSS}\:%c - %m%n
The log file name can then be set two different ways:
As a command line, system property passed to java "-Dlogfile.name={logfile}"
In the java program directly by setting a system property (BEFORE you make any calls to log4j).
System.setProperty("logfile.name","some path/logfile name string");

Adapted from the log4j documentation:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;
public class SimpandFile {
static Logger logger = Logger.getLogger(SimpandFile.class);
public static void main(String args[]) {
// setting up a FileAppender dynamically...
SimpleLayout layout = new SimpleLayout();
FileAppender appender = new FileAppender(layout,"your filename",false);
logger.addAppender(appender);
logger.setLevel((Level) Level.DEBUG);
logger.debug("Here is some DEBUG");
logger.info("Here is some INFO");
logger.warn("Here is some WARN");
logger.error("Here is some ERROR");
logger.fatal("Here is some FATAL");
}
}

Can be also done by this properties define in log4j.properties file
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.maxFileSize=5000KB
log4j.appender.logfile.maxBackupIndex=5
log4j.appender.logfile.File=/WebSphere/AppServer/profiles/Custom01/error.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p [%t] %C %M %c{1}:%L - %m%n

Working and same has been tested
// setting up a FileAppender dynamically...
SimpleLayout layout = new SimpleLayout();
RollingFileAppender appender = new RollingFileAppender(layout,"file-name_with_location",true);
appender.setMaxFileSize("20MB");
logger.addAppender(appender);

Just remove your log4j code and replace this code in your java class it's working good no need to add properties or xml file
SimpleDateFormat dateFormatsd = new SimpleDateFormat("dd-MM-yyyy-hh-mm");
String dateandtime=dateFormatsd.format(new Date());
SimpleLayout layout = new SimpleLayout();
RollingFileAppender appender = new RollingFileAppender(layout,".\\Logs\\log "+dateandtime+".txt",true);
appender.setMaxFileSize("20MB");
logger.addAppender(appender);
The above code will log the logs for every minute.
Thanks

Related

Use log4j.jar in my java file.

I have class file like this, using log4j.jar is easy in eclips IDE. but not through windows command prompt.
import log4j.Logger;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class log4jExample{
/* Get actual class name to be printed on */
static Logger log = Logger.getLogger( log4jExample.class.getName());
public static void main(String[] args)
throws IOException,SQLException {
log.debug("Hello this is an debug message");
log.info("Hello this is an info message");
}
}
and I create log4j properties like this:
# Define the root logger with appender file
log = /usr/home/log4j
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
what should I do to get log records in cmd and file
Just define a ConsoleAppender and the log messages will go both to the file and to the console.
http://logging.apache.org/log4j/1.2/manual.html
Your config file should be
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE, A1
# 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
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

log4j not logging into file

log4j.rootLogger=INFO
log4j.logger.com.app.yum.package.WatchDog=INFO,logfile
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.file=watchdog/watchdog.log
log4j.appender.logfile.maxFileSize=1024KB
log4j.appender.logfile.maxBackupIndex=5
log4j.appender.logfile.append=true
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d | %-5p | %m | %c | %t%n
I am using above config in log4j properties file. I could see a new file has been created but there are no logs inside it.
Instead I see the logs on console. What I am trying to do is log all the logs of particular class in a file watchdog.log.
Below is my logger initialization
private static final Logger logger = LoggerFactory.getLogger(WatchDog.class);
Am I missing anything?
You need to tell the log4j to log on file,
First add:
log4j.rootLogger=INFO, FILE
Then you need to specify the file Appender like:
#settings for FILE: output to file using standard TTCC pattern
#this option backs up the file daily with a date stamp
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
#this option backs up the file after is reaches a specified size
#log4j.appender.FILE=org.apache.log4j.RollingFileAppender
#log4j.appender.FILE.MaxFileSize=1KB
#log4j.appender.FILE.MaxBackupIndex=3
#optionally change the filepath to the log file
log4j.appender.FILE.File=D:/Reliances/reliance90e_NOVO/logs/reliance.log
log4j.appender.FILE.layout=org.apache.log4j.TTCCLayout
log4j.appender.FILE.layout.ContextPrinting=true
log4j.appender.FILE.layout.DateFormat=ISO8601
log4j.appender.FILE.Threshold=DEBUG
and to intialzed the logger you can do:
//From org.apache.log4j.Logger
Logger logger = Logger.getLogger(obj.getClass().getName());
Note: The value are an example and the also i want to show you the different options in the File Appender, also this configurations should be added to your another configurations.

Log4J out to console and file produces warnings/errors log4j:WARN File option not set for appender

I'd like to integrate Log4J logging into my Java application, writing information out to a log file as well as displaying the info at the console. Unfortunately, I've had some trouble getting this off the ground. I'm working with Eclipse Juno on Win 7.
My log4j.properties file:
#configure logfile
log4j.appender.logfile = org.apache.log4j.RollingFileAppender
log4j.appedner.logfile.File = MyAppLog.log
log4j.appender.logfile.Append = true
log4j.appender.logfile.layout = org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern = %-5p %d [%t][%F:%L] : %m%n
#configure 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 = %-5p %d [%t][%F:%L] : %m%n
log4j.rootLogger = debug, logfile, stdout
I belive the above follows the pattern of some other accepted answers on this topic.
I've specifed the location of this log4j.properties file wtih a VM argument:
-Dlog4j.configuration=file:///${workspace_loc}\path\to\file\log4j.properties
I instantiate the logger in my java class:
static Logger logger = Logger.getLogger(MyApp.class.getName());
log a string:
logger.info("barfoo");
This configuration results in the following warnings/errors on launch:
log4j:WARN File option not set for appender [logfile].
log4j:WARN Are you using FileAppender instead of ConsoleAppender?
log4j:ERROR No output stream or file set for the appender named [logfile]
It does not produce the log file. The console logging seems to be working just fine, however.
This will sound stupid - you have a typo. You have log4j.appedner.logfile.File instead of log4j.appender.logfile.File (note the 'n' and 'd' are switched). This is why it's complaining that you haven't set the File.

Issue with log4j log not writing to file

Does anyone see why this log is not writing to file. It is writing to standard out twice but not to the file:
Also, I tried removing the "Stdout" appender and then I don't get any logging at all.
package org.berlin.wicket;
import org.apache.log4j.Logger;
private static final Logger LOG = Logger.getLogger(QuickstartPage.class);
LOG.info("Loading constructor");
log4j.rootLogger=DEBUG,Stdout,mainAppender
log4j.appender.Stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.conversionPattern=%-5p - %-26.26c{1} -
%m\n
log4j.appender.mainAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.mainAppender.file=logs/core.log
log4j.appender.mainAppender.datePattern='.'yyyy-MM-dd
log4j.appender.mainAppender.append=true
log4j.appender.mainAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.mainAppender.layout.ConversionPattern=[%d{MM/dd/yyyy
HH:mm:ss.SSS}] [%C{1}.%M():%L] [%t] [%p] - %m%n
log4j.logger.org.berlin=DEBUG,Stdout,mainAppender
You have two loggers which use the same appender (Stdout), hence why you see entries on the console twice.
As others have mentioned, the properties are case-sensitive, hence why your file appender is not configured correctly.
The File and Append properties are case senstive.
log4j.appender.mainAppender.File=someFileName.log
log4j.appender.mainAppender.Append=true
You should create an instance of FileHandler that writes log to a file called myfile.log.
FileHandler fileHandler = new FileHandler("myfile.log", true);
logger.addHandler(fileHandler);

Can't find log file on server using log4j

I am trying to configure log4j for the first time but its not creating myTest.log file. Below is my log4j.properties file and location of this file is WEB-INF/classes folder.
log4j.rootLogger=INFO, stdout, com.myTest
#tomcat logger
#log4j.logger.org.apache.catalina=DEBUG
log4j.logger.com.myTest=INFO
log4j.logger.org.apache.commons.configuration.PropertiesConfiguration=DEBUG
#appenders
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{yyyy-MM-dd HH:mm:ss} %m%n
log4j.appender.com.myTest=org.apache.log4j.FileAppender
log4j.appender.com.myTest.File=myTest.log
log4j.appender.com.myTest.MaxFileSize=15MB
log4j.appender.com.myTest.MaxBackupIndex=10
log4j.appender.com.myTest.layout=org.apache.log4j.PatternLayout
log4j.appender.com.myTest.layout.ConversionPattern=[%5p] %d{yyyy-MM-dd HH:mm:ss} %m%n
log4j.appender.org.apache.ibatis=org.apache.log4j.FileAppender
log4j.appender.org.apache.ibatis.File=myTest.log
log4j.appender.org.apache.ibatis.MaxFileSize=15MB
log4j.appender.org.apache.ibatis.MaxBackupIndex=10
log4j.appender.org.apache.ibatis.layout=org.apache.log4j.PatternLayout
log4j.appender.org.apache.ibatis.layout.ConversionPattern=[%5p] %d{yyyy-MM-dd HH:mm:ss} %m%n
My controller class is like
#Controller
public class LoginController
{
static final Logger logger = Logger.getLogger(LoginController.class);
#RequestMapping("/login")
public ModelAndView login(){
logger.debug("Test logs");
logger.error("test error");
return new ModelAndView("login");
}
}
But I can't see any myTest.log file in my Apache/log folder. Is this a place it should be?
Jar file I am using is log4j-1.2.16.jar. Is anything else required.
I am using Ubuntu and its first time I am using this.
Put log4j.properties file in build/classes/ folder.
Put file path to ${catalina.home}/logs/myTest.log.
log4j.appender.com.myTest.File=${catalina.home}/log/myTest.log
Path of logs can be checked by writing below code in your LoginController class
Enumeration e = Logger.getRootLogger().getAllAppenders();
while ( e.hasMoreElements() ){
Appender app = (Appender)e.nextElement();
if ( app instanceof FileAppender ){
System.out.println("File: " + ((FileAppender)app).getFile());
}
}
As you have posted in your question the location of log4j.properties file is WEB-INF/classes folder.
To solve the issue try placing the log4j.properties file within src folder of your application.
I encountered the same problem。
On the server machine,log4j could't write log file, but used standout to print log info, it is working.(do you?)
I think is the permissions problem.
so i write log file in tomcat log location(logs/)
log4j.appender.com.myTest.File=${catalina.home}/logs/myTest.log
Hope this works for you!!

Categories