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")
}
}
Related
I am new to the Log4j framework and after reading some stuff i got some fare idea about logging mechanism, but still
i have some doubt about the following properties.
log4j.category.com.cloud.sample=INFO, file, C
log4j.additivity.com.cloud.sample=true
log4j.appender.C=org.apache.log4j.ConsoleAppender
log4j.appender.C.Target=System.out
log4j.appender.C.ImmediateFlush=true
log4j.appender.C.layout=org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern=%-5p %d [%t] %m%n
#log4j.rootLogger=INFO, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
### direct messages to file ###
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${catalina.home}/var/basic/logs/sample.log
log4j.appender.file.Append=true
log4j.appender.file.MaxFileSize=10MB
# mylog.log.10 \u307e\u3067\u4fdd\u6301
log4j.appender.file.MaxBackupIndex=50
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d %5p [%t] %c{1} - %m%n
log4j.rootLogger=INFO, C, file
In the first line of the above code contains two appenders(file, C) after that we will be having appender for both file and C. So as per my understanding logs will of category will be stored to Console and sample.log. Please let me know if i am wrong.
log4j.rootLogger=INFO, A1 and respective properties are not used right?
log4j.rootLogger=INFO, C, file: This line is about root logger, I think in my case it is not useful, because it is defined at the last line and there is no properties defined over here.
Please could any body confirm my understanding and suggest me if any changes required in the above configuration
The root logger resides at the top of the logger hierarchy. It is exceptional in three ways:
it always exists,
its level cannot be set to null
it cannot be retrieved by name.
The rootLogger is the father of all appenders. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy (including rootLogger).
I've seen many questions concerning log4j not writing any files, but my problem is that, log4j does (seem to) work, but not for all files.
My configuration is as follows (I have omitted a few loggers for simplicity, the below lines appear in the order they are in in the file):
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 %5p %c{1}:%L - %m%n
# this logger works without any problems
log4j.appender.errorFile=org.apache.log4j.RollingFileAppender
log4j.appender.errorFile.File=${LOG_HOME}/errors.log
log4j.appender.errorFile.MaxFileSize=20MB
log4j.appender.errorFile.MaxBackupIndex=10
log4j.appender.errorFile.layout=org.apache.log4j.PatternLayout
log4j.appender.errorFile.layout.ConversionPattern=%d %5p %c{1}:%L - %m%n
log4j.appender.errorFile.Threshold=ERROR
# this file is created but always empty
log4j.appender.barcodeScanner=org.apache.log4j.RollingFileAppender
log4j.appender.barcodeScanner.File=${LOG_HOME}/barcodeScanner.log
log4j.appender.barcodeScanner.MaxFileSize=20MB
log4j.appender.barcodeScanner.MaxBackupIndex=5
log4j.appender.barcodeScanner.layout=org.apache.log4j.PatternLayout
log4j.appender.barcodeScanner.layout.ConversionPattern=%d %5p %c{1}:%L - %m%n
# this logger also works
log4j.appender.DoubleDtpaList=org.apache.log4j.RollingFileAppender
log4j.appender.DoubleDtpaList.File=${LOG_HOME}/DoubleDtpaList.log
log4j.appender.DoubleDtpaList.MaxFileSize=20MB
log4j.appender.DoubleDtpaList.MaxBackupIndex=1
log4j.appender.DoubleDtpaList.layout=org.apache.log4j.PatternLayout
log4j.appender.DoubleDtpaList.layout.ConversionPattern=%d %5p %c{1}:%L - %m%n
log4j.rootLogger=error, errorFile
log4j.logger.scanner.BarcodeScanner=debug, barcodeScanner
log4j.logger.util.DetectDoubles=trace, DoubleDtpaList
Using the logger within the BarcodeScanner class yields correct results when using logger.error() (this logs to the errors.log file), but all calls to logger.debug() and logger.info() have no effect.
The variable LOG_HOME is passed as an argument/option when executing the *.jar file.
EDIT 1: I added another (working) logger/appender configuration for clarification. Another piece of information I unfortunately left out ist that I want all logs for the scanner to go to the barcodeScanner.log file (with the errors additionally going to errors.log (root Logger)
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.
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