To use logger with Java, for now I'm using code like this:
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("c:\\MyLogFile.log", true);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.log(Level.WARNING,"My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But it always disturbs me somewhat to add this for every class file:
Logger l = Logger.getLogger("MyLog");
How could I refactor out this duplication?
Is there a better recommended way for logging, which could be less intrusive/less repeative but offers the same or even better functions?
You could make l a private static or private field of the class, but apart from that there is no significant improvement.
(There are some bad ideas, like a public static "global" variable, or a private static declaration in a "universal" base class. But those are BAD IDEAS ... not better ways.)
But, hey, one line of code to declare your local logger object is hardly "intrusive" ... is it?
Logging in every class file is a right way, alougth it is looks a little redundancy.
The important function for logging is that record exception. If we want to directly find where occurs the exception, we should know the class name and the method name.
But you maybe be forget to logging when catch exception.
We're using reflection and static fields and this API: http://commons.forgerock.org/bom/apidocs/org/forgerock/i18n/slf4j/LocalizedLogger.html#getLoggerForThisClass()
You could use project lombok to do this:
project lombok is here
The following is the example from their webpage should it ever not be available. To be clear it still generates the statements in your resulting bytecode, but it stops the bolierplate, now you'll have a smaller statement to but in, its horses for courses but the project team I currently work on like it.
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
#Log
public class LogExample {
public static void main(String... args) {
log.error("Something's wrong here");
}
}
#Slf4j
public class LogExampleOther {
public static void main(String... args) {
log.error("Something else is wrong here");
}
}
#CommonsLog(topic="CounterLog")
public class LogExampleCategory {
public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
}
Vanilla Java
public class LogExample {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
public static void main(String... args) {
log.error("Something's wrong here");
}
}
public class LogExampleOther {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class);
public static void main(String... args) {
log.error("Something else is wrong here");
}
}
public class LogExampleCategory {
private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog");
public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
}
Related
This is my code:
public class Foo {
public static void main(String... args) {
// reconfigure global logging
// do something else
}
}
How can I test this from JUnit (or maybe not) without mocking? I want this main() function to do exactly what it would do normally and then catch its console output for assertions. Of course, without disturbing other tests with the reconfiguration of global logging, as mentioned above. Basically, I need a new JVM to run it.
You can try to set (to mock, actually) System.out before your test, for example:
public class Foo {
public static void main(String... args) {
System.out.print("Console output");
}
}
Test:
#Test
public void canPrint() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
System.setOut(new PrintStream(os));
Foo.main();
assertEquals("Console output", os.toString());
}
I have a singleton class
public class SingletonText {
private static final CompositeText text = new CompositeText(new TextReader("text/text.txt").readFile());
public SingletonText() {}
public static CompositeText getInstance() {
return text;
}}
And TextReader constructor that could throw FileNameEception
public TextReader(String filename) throws FileNameException{
if(!filename.matches("[A-Za-z0-9]*\\.txt"))
throw new FileNameException("Wrong file name!");
file = new File(filename);
}
How can I rethrow it to main and catch it there?
Main class
public class TextRunner {
public static void main(String[] args) {
// write your code here
SingletonText.getInstance().parse();
System.out.println("Parsed text:\n");
SingletonText.getInstance().print();
System.out.println("\n\n(Var8)Task1:");
SortWords.sortWords(SingletonText.getInstance().getText().toString(), "^[AEIOUaeiou].*", new FirstLetterComparator());
System.out.println("\n\n(Var9)Task2:");
SortWords.sortWords(SingletonText.getInstance().getText().toString(), "^[A-Za-z].*", new LetterColComparator());
System.out.println("\n\n(Var16)Task3:");
String result = SubStringReplace.replace(SingletonText.getInstance()
.searchSentence(".*IfElseDemo.*"), 3, "EPAM");
System.out.println(result);
}}
Static block is executed only when class is loaded for the first time, so you can have something as below which will allow you to re-throw the exception. In you main method, you will surround getInstance() invocation in a try-catch block and then in catch you can do whatever you are looking for.
In case of exception, this exception will be thrown and re-thrown (from you static block) only once, at time of class loading. What #Alexander Pogrebnyak has said is also true.
Looking at the code you have provided, since you are always reading text/text.txt files so below approach will work. In case you are looking to read different files and then re-throwing exception then that becomes all together a different story, and you hadn't asked that part neither the code you have provided shows the same. In any case, if that's what you are looking for then:
you need to create a singleton object of your CompositeText class.
create a setter method will create an object TextReader class using the file name string passed.
that setter method will have the try-catch block, and in the catch block you will re-throw the exception so that you can catch again in main method.
P.S.: since static blocks are executed only once when class is loaded and class is loaded only once per JVM (until you have custom class loaders and overriding the behavior) so this ensures that this singleton is thread-safe.
Code:
public class SingletonText {
private static CompositeText text = null;
static{
try {
text = new CompositeText(new TextReader("text/text.txt").readFile());
} catch (FileNameException e) {
// TODO: re-throw whatever you want
}
}
public SingletonText() {}
public static CompositeText getInstance() {
return text;
}
}
try to lazy initialze the singleton.
something like this:
public class SingletonText {
private static CompositeText text;
public SingletonText() {
}
public static CompositeText getInstance() {
if (text ==null) {
text = new CompositeText(new TextReader("text/text.txt").readFile());
}
return text;
}
}
Also, you need to declare the constructor private, and if it multi-threaded application you need to synchronized the new statement with double check locking. see this in wiki:
https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
Enjoy..
You will get java.lang.ExceptionInInitializerError when your singleton static initializer will fail.
As a cause it will have your FileNameException.
If you don't do anything, default exception handler will print the whole stack trace to standard error.
I am extending functionality of a Java project that I inherited that has logging implemented using a class Log that wraps java.util.logging.Logger:
import java.util.logging.*;
public class Log {
// ...
private final Logger log;
I am integrating a third-party library and the problem I've run into is that after I create an object of a class from this library, all logging stops. Or, more precisely, I don't see any log messages in System.err. So in the block below that creates an object of class SomeClass:
public class TopClass {
private static final Log log = new Log(TopClass.class);
// ...
private static SomeClass foo = null;
// ...
public static void main(String[] args) {
// ...
log.severe("SEVERE-BEFORE");
log.info("INFO-BEFORE");
foo = new SomeClass();
log.severe("SEVERE-AFTER");
log.info("INFO-AFTER");
I can see SEVERE-BEFORE and INFO-BEFORE but not SEVERE-AFTER or INFO-AFTER.
How do I figure out what happens with logging during foo's initialization? I have access to some of the source code of the SomeClass library and I searched for any mentions of "log" but did not find any. The library does have a few System.err.priteln() calls. The library also depends on a couple of other libs whose source I don't have access to.
It is possible that the constructor SomeClass of throws an exception.
Try to wrap your code in try-catch.
Something like:
public static void main(String[] args) {
// ...
log.severe("SEVERE-BEFORE");
log.info("INFO-BEFORE");
try
{
foo = new SomeClass();
}
catch (Throwable t)
{
log.severe("an exception was thrown", t);
}
log.severe("SEVERE-AFTER");
log.info("INFO-AFTER");
I was wondering, if it is possible to extend the standard java logger (java.util.logging.Logger;) for another logger level.
The goal is, that there should show up "ERROR" instead of "SEVERE" in the log files.
Is that possible?
Or do I have to use a different logger instead (e.g. Log4j)?
Thanks a lot!
If you just want to print something different than the standard you could set your own formatter, see http://tutorials.jenkov.com/java-logging/formatters.html
If you want to add an additional log level you can do so by subclassing java.util.logging.Level:
public class MyErrorLevel extends java.util.logging.Level {
public MyErrorLevel() {
super("ERROR", 1000);
}
}
Ok, Andreas Vogler's version works. Create this class:
public class MyErrorLevel extends java.util.logging.Level
{
public MyErrorLevel()
{
super("ERROR", 1000);
}
}
To use it in your running program code, you have to do it that way:
logger.log(new MyErrorLevel(),"My Error number one");
If you need more than one errorLevel you can do it that way:
public class MyErrorLevel extends Level
{
public static MyErrorLevel ERROR = new MyErrorLevel ("ERROR", 950);
public static MyErrorLevel SERIOUS_ERROR = new MyErrorLevel("SERIOUS_ERROR", 980);
//...and so on...
private MyErrorLevel(String name, int value)
{
super (name, value);
}
}
In your program code, you can use it like this:
logger.log(MyErrorLevel.ERROR, "my other error");
logger.log(MyErrorLevel.SERIOUS_ERROR, "my significant Error");
Now, if you don't want to specify your own classname (MyErrorLevel.SERIOUS_ERROR) everytime and instead you want to use 'standard-methods' (e. g. like the already existing method logger.info("my information")) you may think about extending the logger itself with new methods. This should (as far as my understanding goes) basically work like that:
public class MyLogger extends Logger
{
public MyLogger(String name, String resourceBundleName)
{
super(name, resourceBundleName);
}
public void error(String msg)
{
super.log(MyErrorLevel.ERROR, msg);
}
public void error(String msg)
{
super.log(MyErrorLevel.SERIOUS_ERROR, msg);
}
}
Now you should be able to call these methods in your code like that:
myLogger.error("my error")
myLogger.seriousError("my serious error")
But I wasnt able to do it:
I couldn't initialize my own logger with:
MyLogger myLogger = MyLogger.getLogger("MyModifiedLogger");
This doesn't compile because of type mismatch (Cannont convert from logger to MyLogger).
I also tried:
MyLogger myLogger = (MyLogger)Logger.getLogger("MyModifiedLogger");
This results in an error message while running:
java.util.logging.Logger cannot be cast to utility.MyLogger
So somehow my extension failed. Any ideas what I am missing?
I never really thought about this before but looking at the following code
public class SomeJavaProgram {
private static String runMe() {
throw new RuntimeException("hi tadsfasdf");
}
private static String name = runMe();
public static void main(String[] args) {
System.out.println("hi there.");
}
}
I never did statics like this in a main before but then I entered scala, and if you have subclasses that start adding defs, exceptions can be thrown before main is even called.
So, in java(not scala), is there a way to catch these exceptions(if I am the superclass and subclasses end up having a static field that throws an exception or static initializer block)....how can I catch all these?
I of course do rely on ONE single definition not throwing which is the
private Logger log = createLoggerFromSomeLoggingLib();
But after that, ideally I would want all exceptions to be logged to the logged file rather than stderr.
That said, I am glad I have always kept the stderr/stdout files along with my logging files now.
Use the static initializer:
private static String name;
static {
try {
name = runMe();
} catch (RuntimeException e) {
// handle
}
}