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)? )
Related
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.
I am using java.util.logging in different classes. The Log Level's default value is INFO. For example in one class Class1 it is setup this way:
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Class1 {
private static final Logger LOGGER = Logger.getLogger(Class1.class.getName());
static {
LOGGER.setLevel(Level.INFO);
for (Handler handler : LOGGER.getHandlers()) {
handler.setLevel(Level.INFO);
}
}
...
}
The above is the same way it is setup in different classes.
Now the Log Level could be changed at runtime. For example suppose it is changed to FINEST at runtime. In this case I want to get all the loggers which have been created so far and then change their Log Level to FINEST. How can I do that? I was thinking about creating another class say LogRepository which has a java.util.List and whenever a LOGGER is created, I add it into the java.util.List of LogRepository. But I think there may be another better way.
I believe this is just a matter of setting the level of the parent logger that all of the instances inherit from.
Logger.getLogger("").setLevel(Level.FINEST);
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 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.
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.