Why use a smart logging tool...
- We can put log output to different presentations like console, log file.
- We can categorize log entries to several level of importance and purpose (Debug/ Info/ Error). And then restrict log output to a certain level when we want.
- Logger provides time, class, other information in log output.
- You can personalize the format of log output.
- And many other…
How to put log4j logging in my code…
- Configuration: Before using Logger class for logging, you need to load configuraion in your program. Otherwise your log will not be printed or put anywhere.
- write a config file "myApp.log.config". Following is a simple configuration to show log in console and store in a file "test.log"
log4j.rootLogger=DEBUG, A1, F1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x -%m%n
log4j.appender.F1=org.apache.log4j.FileAppender
log4j.appender.F1.File=${user.home}/test.log
log4j.appender.F1.layout=org.apache.log4j.PatternLayout
log4j.appender.F1.layout.ConversionPattern=%p %t %c - %m%n
details of configuration... - Log Now! You are ready to log.
- Get the Logger class
Logger logger = Logger.getLogger( MyClass.class );
Logger logger = Logger.getLogger( "ClassName" );- Log your message in appropriate level
logger.error( "Error occurred while parsing", execption );
logger.fatal( "Failed to connect the server" ); - Get the Logger class
Appropriate use of logging levels
Here is a guideline for deciding the logging level when you put a message in the log.
- FATAL: at which point your application or part of application is no longer functional to serve.
- Crash of the application.
- Crash the relevant sub-component.
- ERROR
- Usually when a Java exception occurs.
- Processing of a request is postponed due to some error.
- Processing a request has not cover all features.
- WARN: indicates minor problems
- Factors external to the application. Such as missing or inconsistent input parameters supplied by user.
- Improper initialization, configuration etc.
- INFO:
- Significant non-error events in the normal life cycle of the application.
- When a request is successfully processed in your application.
- DEBUG
- Printing value of a variable or object property in log .
- Non-error events in the normal life cycle of the application
- TRACE
- Usually used for timing information.
4 comments:
This is very good. Vaiya Go ahead...
It was helpful. Can we see some post on how to write custom appenders in future? Like how to write logs in binary/encrypted format.
That is a good suggestion. I'll work out something.
And i'll try post something about configuring appenders.
really helpful. thnx
Post a Comment