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 ^^
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
I have defined the following live template in IntelliJ:
private static final Logger log = LoggerFactory.getLogger($CLASS_NAME$.class);
I use it to insert logger variable to a class.
Is it possible to define so that template also adds
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
to the file if these definitions are still absent?
Define it fully in the Live template:
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger($CLASS_NAME$.class);
and IntelliJ should auto reformat the expression to an import. (Assuming you already have the lib JAR downloaded and configured with IntelliJ).
Edit: As comment says: the Shorten FQ Names check-box should be checked (which it is by default)
Tested with IntelliJ IDEA 15.0.4
Now its possible to add live templates with static imports:
You have to check static import in Options
#org.junit.Test
public void should$EXPR$when$CONDITION$() {
org.junit.Assert.assertThat(null, org.hamcrest.CoreMatchers.is(org.hamcrest.CoreMatchers.nullValue()));
}
This is a stupidly simple example, and yet for some reason it's not working. I must be missing something obvious.
I am trying to make a very simple log4j 2.0 example program. I have added these two jars to the classpath:
log4j-api-2.0-beta8.jar
log4j-core-2.0-beta8.jar
And have done the simplest example possible, using the default configuration:
package testlog;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class TestLog {
static Logger logger = LogManager.getLogger(TestLog.class.getName());
public static void main(String[] args) {
logger.trace("Hello World");
System.out.println("Test over");
}
}
But for some reason, all I get is 'Test over', I never get the Hello World, anywhere I can find anyway. Am I looking in the wrong place? It;s my understanding that with the default configuration it should be printed to the console, with the 'Test Over'. I have changed the log level to info, still the same. I have tried pulling out the Logger functionality into a class, still the same. I am following this tutorial on the log4j documentation page:
http://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration
I can't understand what could possibly be wrong. Could anyone shed any light on what I've done wrong? Thanks in advance.
Update The logger DOES work with logger.error(). This would mean it is a problem with the default filters/level no?
You missed that line in the documentation:
Note that by default Log4j assigns the root logger to Level.ERROR.
Do a
logger.error("Hello World");
and it will be displayed.
If you want to display info and/or trace levels, you have to configure your logger.
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.
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.