Here is my code
package com.my;
import org.apache.log4j.spi.LoggerFactory;
import java.io.*;
import java.util.logging.*;
public class Log {
public static void main(String[] args) {
try{
FileHandler hand = new FileHandler("vk.log");
Logger log = Logger.getLogger("log_file");
log.addHandler(hand);
log.warning("Doing carefully!");
log.info("Doing something ...");
log.severe("Doing strictily ");
System.out.println(log.getName());
}
catch(IOException e){
System.out.println(e)
}
}
}
Your code should work if you delete the superfluous log.getLogger(""); statement and fix the imports.
A couple of comments:
If you have multiple loggers you can selectively turn them on and off. It is conventional to create multiple loggers based on class or package names; e.g.
Logger log = Logger.getLogger(this.getClass());
or
Logger log = Logger.getLogger(SomeClass.class);
You are instantiating and associating the handler programmatically. It is a better idea to put the logging configurations into an XML or properties file, and use one of the configurers to load it and wire up the logging handlers. This allows you ... or the user ... to adjust the logging without modifying your code.
You should probably READ the log4j introduction document that explains the above and other things about using log4j.
The above assumes that you were trying to use log4j. Is you are really trying to use java.util.logging, some details are not exactly right. (And, IMO, you would be better off with using log4j or one of its offspring.)
Your code is more or less fine (check the imports) and should work correctly if you remove the line:
log.getLogger("");
A working implementation of your class would then be:
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class test {
public static void main(String[] args) {
try {
FileHandler hand = new FileHandler("vk.log");
Logger log = Logger.getLogger("log_file");
log.addHandler(hand);
log.warning("Doing carefully!");
log.info("Doing something ...");
log.severe("Doing strictily ");
System.out.println(log.getName());
} catch (IOException e) {
// Handle error.
}
}
}
Can you explain further your problem?
Here are a couple suggestions.
Watch your imports, you are mixing
Log4j or java.util.logging imports
no need to call getLogger() twice
Do something with your exceptions,
even if that means using a
System.out.println() e.printStackTrace() in this test
case. If there were problems thrown,
you were hiding them.
Related
I've found a few examples (even on Stack Overflow) of some programmatic configuration of Logback logging appenders, but as much as I've incorporated into my own setup hasn't worked for me so far. Some examples produce an actual Logger instance, but considering I've already got a Logger being statically instantiated within my class, I want to be able to programmatically enable an Appender that I've defined for unit testing purposes.
Here is my custom appender:
package org.example.logging;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.ArrayList;
import java.util.List;
// Credit to https://stackoverflow.com/a/29077499/5476186
public class TestAppender extends AppenderBase<ILoggingEvent> {
private static List<ILoggingEvent> events = new ArrayList<>();
#Override
protected void append(ILoggingEvent e) {
events.add(e);
}
public static List<ILoggingEvent> events() {
return List.copyOf(events);
}
public static void clear() {
events.clear();
}
}
And in my testing code, I'm trying to configure my TestAppender to "kick in" so that, after invoking this method in my test setup, I can capture the logs and validate them:
package org.example.logging;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;
// ...
// Mostly modeled after https://stackoverflow.com/a/7825548/5476186
private static void startAppender() {
LoggerContext logCtx = (LoggerContext) LoggerFactory.getILoggerFactory();
TestAppender appender = new TestAppender();
appender.setContext(logCtx);
appender.setName("TEST");
// I was hoping this would statically allow the appender to kick in,
// but all of the examples then attach this appender to a Logger instance.
appender.start();
}
Obviously, this isn't working for me. So I guess I have two contingent questions.
Is this possible and, if so, how can I make it work?
If this is not possible, what's the cleanest way to accomplish what I'm trying to do? (Enable/disable appenders during testing without having to manually mess with a config file.)
In one of the threads linked above, I found this answer which looks like one possible solution is to modify the text in the configuration file and to force a reload, but that doesn't seem super clean to me. Another option would be to create my own wrapper Logger factory which I could use to provide loggers with my TestAppender during test execution with dependency injection. I'll probably be creating a wrapper anyway, even though I'm using SLF4J.
Side note: I know that my test code as currently written is pretty tightly coupled with Logback instead of SLF4J, so I'm open to criticism/advice on that issue, too.
If you're using slf4j in your production code, then there is already a project that can help in testing: Its called slf4j-test
In a nutshell, it provides an API to retrieve a "test logger" in the test that will keep all the logged messages in memory so that you'll be able to verify them.
So that you:
Execute a method that logs something
Retrieve a test logger
call getLoggingEvents() on the test logger and verify the logged events
The link that I've provided contains an example of the API as well as maven integration example.
If, alternatively you would like to use logback directly for the tests or something, there is already a ListAppender shipped as a part of logback distribution that allows retrieval of events that have passed through the appender. You can add it programmatically to the logger and use inside the test.
Here you can find a comprehensive example of doing that
In short: the object "logger" is not recognized unlike in many tutorials.
The problem on its own is not very serious and I can easily go around it. However it is very frustrating to see this "logger" stays in red in my intellIj editor. I am going through docs and blogs and I don't see what the problem is.
My snippet:
#Override
public void insertTicketStatut(TicketStatut pTicketStatut) {
String vSQL = "INSERT INTO statut {id, libelle} VALUES {:id, :libelle}";
BeanPropertySqlParameterSource vParams = new BeanPropertySqlParameterSource(pTicketStatut);
NamedParameterJdbcTemplate vJdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());
try {
vJdbcTemplate.update(vSQL, vParams);
} catch (DuplicateKeyException pE){
logger.error("Le TicketStatut existe déjà ! id="+ pTicketStatut.getId(),pE);
}
}
Hovering over logger shows "Cannot resolve symbol 'logger'
Thanks for your help.
Recommend using sl4j
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Then instantiate:
//generic way to declare logger to be able to copy/paste to other classes
//without changing the class name
private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
In dependency, include the binding for sl4j implementation ( can be log4j ).
Can refer here:
logging-with-slf4j
The logger needs to be either instantiated or better injected. It seems that you did not do that. When you use some kind of logging framework like log4j the initialisation would look like this:
static Logger logger = Logger.getLogger(MainApp.class.getName());
When you show us the whole class we can see more details and can guess better.
An tutorial for log4j and spring can be found here.
Indeed, I didn't managed properly my imports:
I added:
private final Log logger = LogFactory.getLog(TicketDaoImpl.class);
from
org.apache.commons.logging.Log;
Stupid lack of attention.
I am having a look also at the doc from log4j/ sl4j on Baeldung. Thanks ^^
I want to distribute a lib relying on the SLF4J logger interface. What is the best practice way to obtain the logger which integrate nicely into any other project? Sorry for the unstructured question style, I'm still trying to figure out how all this stuff is glued together.
In other projects I always use this piece of code, because I want to obtain a custom logger:
private final static Logger LOGGER = LoggerFactory.getILoggerFactory().getLogger(NAME_OF_APP);
If I create the class org.slf4j.impl.StaticLoggerBinder and have it some other lib, does the therein defined factory get used even if I just call LoggerFactory.getLogger(NAME_OF_APP) or is some default slf4j factory used?
I want the user to be able to use his own factory and logger, so which way is to perfere, and most of all why?
I'm not sure I fully understand what you are trying to do.
SLF4J is composed of two parts. First the API which you use in your lib to code your logging calls. And secondly the implementation which you use during your development to do logging, but DO NOT set as a dependency of the lib.
Because SLF4J looks for the implementations on the class path the developers using our lib can simple include any implementation they want. Sometimes is some quite strange ways :-) They can use a range of prebuilt implementations or code their own. It's up to them.
I don't think you need to do anything more than just use SLF4J's API as is.
From http://slf4j.org/manual.html
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(HelloWorld.class);
logger.info("Hello World");
}
}
So, always use LoggerFactory.getLogger(...). The argument allow the logger backend to determine the behavior of the logger returned to you.
I am not sure I fully understand what your scenario is.
But from my viewpoint, what you want is a distributed logging component.
A simple approach to do that is a socket appender. And a full feature component for distributed logging may like Facebook's scribe.
Use Logger static wrapper from jcabi-log:
import com.jcabi.log.Logger;
public class MyLibraryClass {
public void foo() {
Logger.info(this, "some information");
}
}
All logs will be sent through SLF4J.
In my output I have JUL logging messages from Jersey like this
03.12.2010 14:14:55 com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
Programmatically I wanted to swich them off so I tried
Logger.getLogger("com.sun.jersey.api.core.PackagesResourceConfig").setLevel( Level.SEVERE );
or
Logger.getLogger("com.sun.jersey").setLevel( Level.SEVERE );
but this don't work.
Funny enough this global configuration works:
Logger.getLogger( "com" ).setLevel( Level.SEVERE );
or
Logger.getLogger( "" ).setLevel( Level.SEVERE );
WHY?
I had some problems with this so I thought I'd put code in with imports to avoid confusion. I tested this and it works in my mini webserver configuration. Again, I included the whole server implementation for completeness.
import java.io.IOException;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.net.httpserver.HttpServer;
public class WebServer {
private HttpServer webServer;
private final static Logger COM_SUN_JERSEY_LOGGER = Logger.getLogger( "com.sun.jersey" );
static {
COM_SUN_JERSEY_LOGGER.setLevel( Level.SEVERE );
}
public void start() throws IOException {
System.out.println("Starting WebServer\n");
webServer = createHttpServer();
webServer.start();
System.out.println(String.format("\nWeb Server started:" + "%sapplication.wadl\n", getURI()));
}
public void stop() {
webServer.stop(0);
}
public static HttpServer createHttpServer() throws IOException {
ResourceConfig rc = new PackagesResourceConfig("com.daford");
return HttpServerFactory.create(getURI(), rc);
}
private static URI getURI() {
return UriBuilder.fromUri("http://localhost/").port(4444).build();
}
}
The loggers returned by Logger.getLogger() are WeakReferences. So directly after you set the appropriate level, they may get garbage collected, since you do not retain any reference to it, thus deleting your setting.
Store your logger in a variable with an appropiate scope to keep your settings.
Credits to John Smith above, but here is the one line answer with the right package name:
Logger.getLogger("org.glassfish.jersey").setLevel(Level.SEVERE);
No imports necessary, these come from java.util.
And let this be a lesson to all of you in Unix Philosophy's rule of silence: when you have nothing erroneous to say, shut the hell up.
Essentially each logger instance has a loglevel. However, when you retrieve a logger instance via Logger.getLogger() you are more than likely creating a new instance of a new logger. Since you aren't keeping a reference to the Logger it instantly goes out of scope and your change is lost.
The reason Logger.getLogger("") and Logger.getLogger("com") work for you is that persistent loggers are already being created for those two levels, which means you are retrieving those loggers which remain persistent.
One simple fix is to use the LogManager class in JUL:
LogManager.getLogManager().setLevel("com.sun.jersey", Level.SEVERE);
There is a great article on O'reilly that should help you.
I am placing a logging.properties in the WEB-INF/classes dir of tomcat
I would like to log to two different files. For example: org.pkg1 goes to one file and org.pkg2 goes to a separate file.
I can get one file configured, but not two. Is that possible?
I finally figured this out. In tomcat they extend java util logging ("JULI") to enable this functionality. Here's a logging.properties file that I put in the WEB-INF directory that finally accomplished what I was after......:
handlers=1console.java.util.logging.ConsoleHandler, 2jsp.org.apache.juli.FileHandler, 3financials.org.apache.juli.FileHandler
.handlers=1a.java.util.logging.ConsoleHandler
jsp.level=ALL
jsp.handlers=2jsp.org.apache.juli.FileHandler
org.apache.jasper.level = FINE
org.apache.jasper.handlers=2jsp.org.apache.juli.FileHandler
org.apache.jsp.level = FINE
org.apache.jsp.handlers=2jsp.org.apache.juli.FileHandler
com.paypal.level=ALL
com.paypal.handlers=3financials.org.apache.juli.FileHandler
3financials.org.apache.juli.FileHandler.level=ALL
3financials.org.apache.juli.FileHandler.directory=${catalina.base}/logs
3financials.org.apache.juli.FileHandler.prefix=financials.
2jsp.org.apache.juli.FileHandler.level=ALL
2jsp.org.apache.juli.FileHandler.directory=${catalina.base}/logs
2jsp.org.apache.juli.FileHandler.prefix=jsp.
1console.java.util.logging.ConsoleHandler.level=FINE
1console.java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
Speaking of logging.properties configuration, I did not found any mechanism to use more that one appender. I made simple workaround that works for me.
public class CustomAFileHandler extends FileHandler {
public DebugFileHandler() throws IOException, SecurityException {
super();
}
}
public class CustomBFileHandler extends FileHandler {
public DebugFileHandler() throws IOException, SecurityException {
super();
}
}
And my logging.properties
...
handlers=<pkg_name>.CustomAFileHandler, <pkg_name>.CustomBFileHandler, java.util.logging.ConsoleHandler
<pkg_name>.CustomAFileHandler.level=ALL
<pkg_name>.CustomAFileHandler.pattern=%h/A%u.log
<pkg_name>.CustomAFileHandler.limit=50000
<pkg_name>.CustomAFileHandler.count=1
<pkg_name>.CustomAFileHandler.formatter=java.util.logging.SimpleFormatter
<pkg_name>.CustomBFileHandler.level=ALL
<pkg_name>.CustomBFileHandler.pattern=%h/B%u.log
<pkg_name>.CustomBFileHandler.limit=50000
<pkg_name>.CustomBFileHandler.count=1
<pkg_name>.CustomBFileHandler.formatter=java.util.logging.SimpleFormatter
...
There's no easy way to get two handlers of the same type with java.util.logging classes that have different arguments. Probably the simplest way to do this is to create a FileHandler subclass in your logging.properties that passes the appropriate arguments to enable your logging to take place, such as:
org.pkg1.handlers=java.util.logging.FileHandler
org.pkg2.handlers=org.pkg2.FileHandler
java.util.logging.FileHandler.pattern="org_pkg1_%u.%g.log"
org.pkg2.FileHandler.pattern="org_pkg2_%u.%g.log"
org/pkg2/FileHandler.java:
package org.pkg2;
import java.util.logging.*;
public class FileHandler extends java.util.logging.FileHandler {
public FileHandler() {
super(LogManager.getLogManager().getProperty("org.pkg2.FileHandler.pattern"));
}
}
It is possible using pure jdk also (try with jdk 7 or jdk 8).
Just create custom file handler; use that similar to "java.util.logging.FileHandler".
public class JULTestingFileHandler extends FileHandler {
public JULTestingFileHandler() throws IOException, SecurityException
{
super();
}
}
user properties file;
com.xxx.handlers = com.xxx.JULXXXFileHandler
com.xxx.JULXXXFileHandler.pattern = ./logs/test1_test2.%u.%g.log
Having the same problem myself with java.util.logging and not quite satisfied with the given answers, I just found in the documentation:
2.2 Changing the Configuration
Here's a small program that dynamically adjusts the logging
configuration to send output to a specific file and to get lots of
information on wombats. The pattern "%t" means the system temporary
directory.
public static void main(String[] args) {
Handler fh = new FileHandler("%t/wombat.log");
Logger.getLogger("").addHandler(fh);
Logger.getLogger("com.wombat").setLevel(Level.FINEST);
...
}
So, it seems you can't do it just from the .properties file as can't instantiate several appenders, but you can do it programmatically. Also it should be possible using the LoggerManager