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.
Related
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.
I've having issues getting logging set up properly on my development app server (launched from Eclipse). I have the correct logging.properties location in my appengine-web.xml, and the most global parameter is working:
.level=ALL
If I change that to INFO everything quiets down and all is good. But trying to add any sort of override for my packages appears to do nothing at all:
.level=ALL
com.company.level=INFO
(I am using my real package name, using the above as an example)
When I try to a full package path such as com.company.user.level or even a class name such as com.company.user.User.level I still get no change. I've also tried moving my entry above and below the .level statement with no luck. As a last resort I tried taking out .level altogether, but that resulted in no change to my custom class logging.
Between each change I fully stop and restart the development appserver to make sure the file is re-read. Again, if I change .level I see a change in logging level output, but nothing else works. I'm stumped? Any suggestions?
AppEngine SDK: 1.9.17 (1.9.18 is the latest as of this writing but there is nothing to indicate this would be fixed in the change logs).
Thanks!!
UPDATE (Solution)
Thanks to #farrellmr below!!
I was doing the following:
private static final Logger log = Logger.getLogger("MyClass"); // wrong
When I should have been doing:
private static final Logger log = Logger.getLogger(MyClass.class.getName()); // correct
You need to define your logger as -
package test;
private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName());
Then you can define your package log configuration as -
test.level = INFO
I have a project containing classes.
I would like to do logging per class instead of wrapping them up altogether in a single log file. I am using Java.
Like for example I have
foo.bar.class1
foo.bar.class2
How can I achieve log file per class?
So that I could have a log file named "class1.log" and "class2.log" containing their own respective log data. What should I do in log4j.properties or on classes?
Any help would be appreciated, thanks.
I'm not sure you can do this in log4j.xml or log4j.properties. So what you can actually do is this (untested, but should work in this fashion):
static {
Logger LOG = LoggerFactory.getLogger(MyClass.class);
try {
((FileAppender)LOG.getAppender()).setFile("class-" + MyClass.name());
} catch (...) {}
}
I have a webapplication and I want to use a different log for every user, so I can have a "history" of what the user did on the system.
This is what I have so far:
import java.io.File;
import java.io.IOException;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.Logger;
public class LogManager {
public Logger getLog(String username) throws IOException{
SimpleLayout layout = new SimpleLayout();
FileAppender appender = new DailyRollingFileAppender(layout, "users"+File.pathSeparator+username+File.pathSeparator+username, "'.'yyyy-MM");
// configure the appender here, with file location, etc
appender.activateOptions();
Logger logger = Logger.getRootLogger();
logger.addAppender(appender);
return logger;
}
}
The problem is that, as a webapplication, is multithreaded, so AFAIK I can't use RootLogger all the time and change the appenders depending on the user who I'm logging. I think I should create different Logger for each user, but is that correct?
Try switching to logback (log4j's successor). It comes with a SiftingAppender which can be used to separate (or sift) logging according to a given runtime attribute, which would be "userid" in your case. The documentation contains an example for separating logs based on userid.
I would suggest using a log context information to record the user for any particular action, and include that in your log records.
Then whenever you need the log for a particular user, trawl through the single log file. If you need all the files split, do it when the log rotates. This post-processing will be a lot simpler than keeping an open file for every user concurrently.
The "Nested Diagnostic Context" is meant for such a use case - you can stamp each log statement with an id to identity the user (like an IP address, username, etc)
more here: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html
(edit: here another useful post on NDC: When to use 'nested diagnostic context' (NDC)? )
May I know what is the best practice of using org.apache.commons.logging.LogFactory.getLog?
For me, I use it the following way :
public class A
{
private static final Log log = LogFactory.getLog(A.class);
}
public class B
{
private static final Log log = LogFactory.getLog(B.class);
}
So, if I have 100 of classes, 100 of static log object will be created?
Or is it best to do it this way?
public class A
{
private static final Log log = LogFactory.getLog(Main.class);
}
public class B
{
private static final Log log = LogFactory.getLog(Main.class);
}
All the 100 classes are referring to a same single same log?
Thank you.
Please remember the 'static problem', which most of java developer ignore and which affect log4j, java.util.Logger, and SLF4J as well. You can read about it in the Apache Commons Wiki. As reported, if you're developing a library, planning to release it in a container (such as a j2ee container), shared among many application, is better use something like
private transient final Log logger = LogFactory.getLog( this.getClass() );
The first option - have a logger per class (or functionality). As most logging systems - log4j, logback, java util logging, etc. have the notion of logger hierarchy, you can match that to your package hierarchy and have finer control of which functionality you want to be logged at which level. For example:
com.example=WARN # global setting
com.example.web=INFO # increase logging for the web controllers
com.example.dao=DEBUG # trying to track bugs in the database layer
In the vast majority of cases, your way is the way to go.
The main advantage is that there is a logger (or category, or whatever) for each class that can be configured individually, like
log4j.logger.org.springframework.transaction=DEBUG
(assuming log4j) which will set the log level just for that class or package. If you use only one logger, you cannot do that.