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
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
Below is the log4j properties file content. I am trying to write WARN logs to two differnt different log filesBY by define two log appenders as shown below.
Problem : The logs are wrting into both the files (duplicate) .
log4j.rootLogger=WARN, A1, xmlout, GPSMSPLogger
#log4j.rootLogger=DEBUG, xmlout
log4j.logger.mailLogger=ALL, mail
log4j.category.com.moodys=INFO
# Setting additivity to false
# For not writing same logs into two files
# R3'13
log4j.additivity.org.apache=false
log4j.additivity.A1=false;
log4j.additivity.GPSMSPLogger=false;
log4j.logger.GPSMSPLogger=DEBUG,GPSMSPLogger
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.threshold=DEBUG
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c %x %m%n
# xmlout is set to be a DatedFileAppender
log4j.appender.xmlout=biz.minaret.log4j.DatedFileAppender
log4j.appender.xmlout.Threshold=DEBUG
#log4j.appender.xmlout.Directory=e\:\\logs\\surveillance.
#log4j.appender.xmlout.Prefix=surveillance
#log4j.appender.xmlout.Suffix=.log
log4j.appender.xmlout.Append=true
log4j.appender.xmlout.layout=org.apache.log4j.xml.XMLLayout
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
#log4j.appender.mail.To=dmitry.nikelshpur#moodys.com
#log4j.appender.mail.To=valeriy.vinnychuk#moodys.com
log4j.appender.mail.To=Moody's-SFGSMART#moodys.com
log4j.appender.mail.From="SFG SMART Application Mailer [Dmitry Nikelshpur]"
# Q2'12
#log4j.appender.mail.SMTPHost=mdynycmsxswp.moodys.com
log4j.appender.mail.SMTPHost=${SMTP.MAIL.SERVER}
# Q2'12
log4j.appender.mail.Threshold=ERROR
log4j.appender.mail.BufferSize=1
log4j.appender.mail.Subject=Test Surveillance logger email handler *** PLEASE DISREGARD ***
log4j.appender.mail.layout=com.moodys.sfg.smart.util.SMARTMailerHTMLLayout
log4j.additivity.mailLogger=true
log4j.appender.mail.layout.LocationInfo=true
# R3'13
# Setup GPSMSPLogger
log4j.appender.GPSMSPLogger=biz.minaret.log4j.DatedFileAppender
log4j.appender.GPSMSPLogger.layout=org.apache.log4j.PatternLayout
log4j.appender.GPSMSPLogger.layout.ConversionPattern=%d [%t] %-5p %c %x %m%n
log4j.appender.GPSMSPLogger.Directory=${msp.log.directory}
log4j.appender.GPSMSPLogger.Prefix=gps_msp.
log4j.appender.GPSMSPLogger.Suffix=.log
log4j.appender.GPSMSPLogger.Threshold=DEBUG
below is the code used to log:
public class GPSMSPLogger {
public static Logger getLogger(){
return Logger.getLogger("GPSMSPLogger");
}
public static void main(String arg[]){
getLogger().info("Log example INFO.......... ");
}
}
You need to remove the trailing semicolons on these lines:
log4j.additivity.A1=false;
log4j.additivity.GPSMSPLogger=false;
The additivity value should be either true or false, not false;
I am using MyBatis3 I need a way to log all my select, insert, update statements to my log4j log file.
Here is my log4j file. Please help
# Root logger option
log4j.rootLogger=INFO, file, stdout
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=test.log
log4j.appender.file.MaxFileSize=2MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Direct log messages to 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=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
You can see the Log4J configuration info here. In short - you need to set Log4J loglevel to DEBUG or TRACE on your mapper or mapper package or specific mapper method. E.g. log4j.logger.org.mybatis.example.BlogMapper.selectBlog=TRACE. TRACE will print SQL, params and resultsets, and DEBUG will print SQL and params only.
I found a way, putting in so others can benefit too
In order to log sql statements download Simple Logging Facade for Java (download slf4j here)
Added the following to my classpath, apart from regular mybatis, odbc and oracle jars
log4j-xxxx.jar
log4j-over-slf4j-xxxx.jar
log4j-rolling-appender.jar
slf4j-api-xxxx.jar
slf-log4j12-xxxx.jar
Note: xxxx is appropriate version here
and append the following lines in my log4j (see my question)
# logger debug
log4j.logger.test.Log4jTestMyBatis=DEBUG, convert
log4j.appender.convert = org.apache.log4j.ConsoleAppender
log4j.appender.convert.layout=org.apache.log4j.PatternLayout
log4j.appender.convert.layout.ConversionPattern=[%d{HH:mm:ss}] %-5p %c{3} %x - %m%n
# end logger debug
# mybatis loggers #
log4j.logger.com.ibatis=DEBUG, convert
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG, convert
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG, convert
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG, convert
Here is a Groovy class example that I used for testing
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.PropertyConfigurator;
import com.abc.db.ConfigInfo;
import com.abc.db.ConfigInfoExample;
import com.abc.db.client.ConfigInfoMapper;
import com.abc.db.init.DatabaseConnectivity;
class Log4jTestMyBatis {
static Logger logger = LoggerFactory.getLogger(Log4jTestMyBatis.class)
static main(args) {
PropertyConfigurator.configure(Log4jTestMyBatis.class.getResource("log4j.properties"));
DatabaseConnectivity.init()
SqlSession newABCSession = DatabaseConnectivity.getNewABCSessionFactory().openSession()
ConfigInfoMapper mapper = newABCSession.getMapper(ConfigInfoMapper.class)
ConfigInfoExample qExample = new ConfigInfoExample()
qExample.createCriteria().andProjectIdEqualTo("0-12170")
List<ConfigInfo> ctlist = mapper.selectByExample(qExample)
logger.debug(ctlist.get(0).getCfgName())
newABCSession.close()
logger.debug("debug")
}
}
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!
In my Java console app, I want to log certain events to a log file and certain others to console. This is what I've got now
log4j.rootLogger=error, 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=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.L1=org.apache.log4j.FileAppender
log4j.appender.L1.layout=org.apache.log4j.PatternLayout
log4j.appender.L1.layout.ConversionPattern=%-22d{dd/MMM/yyyy HH:mm:ss} – %m%n
log4j.appender.L1.file=failedtoaddusers.log
In my Java app, I instantiate two log instances using
private static Logger log = Logger.getLogger(ActiveDirectoryManage.class);
private static Logger failedToAddUsersLogger = Logger.getLogger("FailedToAddUsersLogging");
My issue is that failedToAddUsersLogger.warn("xyz") also writes to the console in addition to the log file failedtoaddusers.log.
I just want it to write to the log file and not to the console.
How do I accomplish that?
You need to set additivity to "false" (read more on logger additivity in the Appenders and Layouts section of the log4j manual):
log4j.additivity.FailedToAddUsersLogging=false
log4j.logger.FailedToAddUsersLogging = your level, L1
Also, make sure you have one of new versions of log4j, "additivity" setting was not available from beginning.