Personal notes on Java
For other technologies like HTML, CSS, .NET, PHP, etc. check my other blog

BareTail

Baretail is a free Log File Monitoring tool.
Many features:
  • line highlighting;
  • you can create batch files to open related log files together, ex:
    SET SERVER=TEST
    SET DIR=\Logs\Applications\
     
    START baretail.exe \\%SERVER%%DIR%Application1.Console.log \\%SERVER%%DIR%Application2.Console.log \\%SERVER%%DIR%Application3.log
  • many more...
References:


Log4J

References:

Main concepts:

  • "Appender": takes care of sending the formatted output to its destination (ex. console; file; etc.).
  • "Layout" is associated, by the user, with an appender and is responsible for formatting the logging request according to the user's wishes; (ex. print the logging level; class and method line; timestamp; etc.)
    Ex. of a layout definition for an appender in a .properties file:
    log4j.appender.fileAppender.layout.ConversionPattern=[%d{ABSOLUTE}] %5p %c{1}:%L - %m%n
    This and other formating options can be found on the: PatternLayout class of the standard log4j distribution.
    Table of conversion characters:
    Conversion Character Effect
    c Used to output the category of the logging event. The category conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.
    If a precision specifier is given, then only the corresponding number of right most components of the category name will be printed. By default the category name is printed in full.
    For example, for the category name "a.b.c" the pattern %c{2} will output "b.c".
    C Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.
    If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form.
    For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass".
    WARNING Generating the caller class information is slow. Thus, use should be avoided unless execution speed is not an issue.

    d Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed.
    The date format specifier admits the same syntax as the time pattern string of the SimpleDateFormat. Although part of the standard JDK, the performance of SimpleDateFormat is quite poor.
    For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying AbsoluteTimeDateFormat, DateTimeDateFormat and respectively ISO8601DateFormat. For example, %d{ISO8601} or %d{ABSOLUTE}.
    These dedicated date formatters perform significantly better than SimpleDateFormat.

    F Used to output the file name where the logging request was issued.
    WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.
    l Used to output location information of the caller which generated the logging event.
    The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses.
    The location information can be very useful. However, its generation is extremely slow and should be avoided unless execution speed is not an issue.
    L Used to output the line number from where the logging request was issued.
    WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.
    m Used to output the application supplied message associated with the logging event.
    M Used to output the method name where the logging request was issued.
    WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.
    n Outputs the platform dependent line separator character or characters.
    This conversion character offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator.
    p Used to output the priority of the logging event.
    r Used to output the number of milliseconds elapsed from the construction of the layout until the creation of the logging event.
    t Used to output the name of the thread that generated the logging event.
    x Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.
    X Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The X conversion character must be followed by the key for the map placed between braces, as in %X{clientNumber} where clientNumber is the key. The value in the MDC corresponding to the key will be output.
    See MDC class for more details.
    % The sequence %% outputs a single percent sign.

Logging levels:

Level Description
OFF The highest possible rank and is intended to turn off logging.
FATAL Severe errors that cause premature termination. Expect these to be immediately visible on a status console.
ERROR Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
WARN Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
INFO Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
DEBUG Detailed information on the flow through the system. Expect these to be written to logs only.
TRACE Most detailed information. Expect these to be written to logs only.

Sample .properties file

To configure log4j for your project you must add a file named "log4j.properties" (or alternatively a log4j.xml) into your project classpath (to do this I usually just paste the file in the projects "src" folder and then Eclipse will add it to the bin folder).
TIP: use this query on google to find many other sample files  log4j.properties filetype:properties.
#DEFINE A CONSOLE APPENDER:
log4j.appender.consoleAppender = org.apache.log4j.ConsoleAppender
#define the layout for the console appender:
log4j.appender.consoleAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=[%d{HH:mm:ss.SSS}] %5p %l - %m%n

#DEFINE A FILE APPENDER (direct log messages to a log file)
log4j.appender.fileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.fileAppender.File=C:\\logs\\TesteLogger.log
log4j.appender.fileAppender.MaxFileSize=1MB
log4j.appender.fileAppender.MaxBackupIndex=1
log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppender.layout.ConversionPattern=[%d{ABSOLUTE}] %5p %c{1}:%L - %m%n

# DEFINE ROOT LOGGER OPTIONS
# the first attribute is the logging level (the level specified and above will be logged)
# the other attributes: map our console appender and file appender as a root logger (means all log messages will go to this appenders)
log4j.rootLogger = DEBUG, fileAppender, consoleAppender

# Print only messages of level WARN or above in the package novaPack
log4j.logger.novaPack=WARN

Logging Exceptions trick

Note that there is a subtle difference between the method override log#(String, Exception) and log#(Exception), ex:
try {
 Integer.parseInt("3d");
} catch (Exception ex) {
 log.error(ex); // only logs the Exception message
 log.error("Some text here", ex); // logs the full stack trace!
}

Configure log4j

Add log4j into your project

  • Web apps: (TODO)
  • Standalone apps: 

To use log4j in you project you just need to:
  • add the log4j jar into your projects classpath
    Ex. of its location: C:\apache-log4j-1.2.17\log4j-1.2.17.jar;
  • add a file named "log4j.properties" or log4j.xml into your project's classpath.
    I usually just paste it on the projects "src" folder (and then Eclipse will automatically copy it to the bin folder).
    see examples of the contents of this file further down on this page.
  • if you want you can add the log4j javadoc too
    my preferred way of doing this is to create an eclipse user library so that I can reuse it on the fly in multiple projects.

Preferred way: create a user defined library in eclipse

This way that you can reuse the configuration in multiple projects inside eclipse (then you just need to import this library to have the jar and its associated javadoc).
To do this:
  • Create a new user library and add the log4j jar:
    Project -> Properties -> Java Build Path -> Libraries -> Add Library -> User Library -> User Libraries -> New -> Add external jars -> Select the (ex) C:\apache-log4j-1.2.17\log4j-1.2.17.jar -> Open.
  • Associate the javadoc:
    Expand the just created library tree -> Select "Source Attachement" -> Edit... -> External location -> External folder -> C:\apache-log4j-1.2.17\src\main\java\ -> OK

Alternatively you can do it manually for each project:

  • Add the jar:
    Project -> Properties -> Java Build Path -> Libraries -> Add External Jars... -> Select the (ex) C:\apache-log4j-1.2.17\log4j-1.2.17.jar
  • Associate javadoc:
    For ex.: inside Eclipse type "Logger l;" Then Ctrl + click the "Logger"  class name -> on the new screen click the "Attach source..." button -> "Add external folder" -> browse to the log4j folder on your system and choose the "\src\main\java\" folder inside it.
    Sample location: C:\apache-log4j-1.2.17\src\main\java\ 




Sem comentários:

Enviar um comentário