• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Presentation log4 j
 

Presentation log4 j

on

  • 1,247 views

Presentation of Log4J framework

Presentation of Log4J framework

Statistics

Views

Total Views
1,247
Views on SlideShare
1,239
Embed Views
8

Actions

Likes
1
Downloads
0
Comments
0

1 Embed 8

http://www.linkedin.com 8

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Le nom du POJO correspond, par défaut, au nom de la table. Le nom des membres du POJO correspondent, par défaut, aux noms des champs de la table. @Id on peut spécifier une stratégie de génération de ID (default == non générée) - @GeneratedValue(strategy=GenerationType.AUTO) - @GeneratedValue(strategy=GenerationType.TABLE) - @GeneratedValue(strategy=GenerationType.SEQUENCE) - @GeneratedValue(strategy=GenerationType.IDENTITY)
  • Par défaut, dans une relation, le join column sera formé de la sorte: _ Donc ici: D_ID
  • Ici le propriétaire de la relation est Employee, c’est lui qui a la foreign key. Donc ParkingSpace a seulement besoin de spécifier sur quel champs la relation est mappé dans la classe propriétaire de la relation. Si la FK == PK, on peut utiliser @PrimaryKeyJoinColumn au lieu de @JoinColumn(name= …) Dans une relation bidirectionnelle, une seule des entité « possède » la relation. L’entité propriétaire de la relation est celle qui déclare la « join column ».
  • Ici le propriétaire de la relation est Employee, c’est lui qui a la foreign key. Donc ParkingSpace a seulement besoin de spécifier sur quel champs la relation est mappé dans la classe propriétaire de la relation. Si la FK == PK, on peut utiliser @PrimaryKeyJoinColumn au lieu de @JoinColumn(name= …) Dans une relation bidirectionnelle, une seule des entité « possède » la relation. L’entité propriétaire de la relation est celle qui déclare la « join column ».

Presentation log4 j Presentation log4 j Presentation Transcript

  • http://logging.apache.org/log4j/docs/ Sylvain Bouchard
  • Agenda
    • Definition
    • Basic features
    • Level
    • Appenders
    • Loggers
    • Layouts
    • Filters
    • Tips
    • - Logging is a low-tech method for debugging applications.
    • - Logging can also be viewed as an auditing tool.
    • Applicability
      • Debuggers are not always available for multi-threaded or distributed applications.
    • Advantages
      • Debugging sessions are transient , logging is persistent .
    • Disadvantages
        • Logging can slow down an application.
        • Can be hard to locate relevant information for large log outputs.
    • The central issue in logging is the categorization of logging statements.
    Logging, a definition
  • Agenda
    • Definition
    • Basic features
    • Level
    • Appenders
    • Loggers
    • Layouts
    • Filters
    • Tips
  • Basic features of any logging library are
    • control over which logging statements are enabled or disabled
      • The first feature corresponds to the Logger , the central class in the log4j package.
    • manage output destinations
      • The second feature is implemented by Appenders . There are appenders for files, the console, Unix Syslog, NT Event Log, remote servers, SMTP e-mail, etc.
    • manage output format
      • The third feature is implemented by Layouts . The most popular layouts are the PatternLayout and HTMLLayout
  • Agenda
    • Definition
    • Basic features
    • Level
    • Appenders
    • Loggers
    • Layouts
    • Filters
    • Tips
  • Level
    • Allows you to prioritize your logged messages
      • TRACE , DEBUG , INFO , WARN , ERROR and FATAL
      • Other priorities possible but usually unnecessary
    • Determines which log items are actually logged
      • For example, a given line of code might always attempt to log an item at Debug level but if the logger tree is not set to log items below Error level then the log message will be ignored and not make it to an appender.
  • Agenda
    • Definition
    • Basic features
    • Level
    • Appenders
    • Loggers
    • Layouts
    • Filters
    • Tips
  • Appenders
    • ConsoleAppender, FileAppender, RollingFileAppender, DailyRollingFileAppender, SMTPAppender, JDBCAppender, NTEventLogAppender, …
    • Multiple appenders can be used
      • One appender could be used for auditing while another is used for general logging
    • An appender element must have name and class attributes. The name is the value used to reference the appender in the rest of the configuration file. The class attribute should be the fully qualified class name of the appender class to use (ie  org.apache.log4j.ConsoleAppender ).
    • An appender element can also contain child elements:
      • 0 or 1 errorHandler element - <yet to be described>
      • 0 or more param elements - Each appender can be configured with setting specific to the functioning of the appender.
    <!ELEMENT appender (errorHandler?, param*, layout?, filter*, appender-ref*)> <!ATTLIST appender name ID #REQUIRED class CDATA #REQUIRED > log4j.dtd
      • 0 or 1 layout element - Not all appenders use or require a layout. For appenders that do, the layout element defines what layout class to use. The layout element has one attribute, class, which is the fully qualified class name of the layout class to use. Similar to the appender element, the layout element is allowed to have 0 or more param child elements.
      • 0 or more filter elements.
      • 0 or more appender-ref elements
    <appender name=&quot;console&quot; class=&quot;org.apache.log4j.ConsoleAppender&quot;> <param name=&quot;Target&quot; value=&quot;System.out&quot;/> <layout class=&quot;org.apache.log4j.PatternLayout&quot;> <param name=&quot;ConversionPattern&quot; value=&quot;%-5p %c{1} - %m%n&quot;/> </layout> </appender> A simple example
  • Appenders Configuration Example <appender name=&quot;FileAppender&quot; class=&quot; org.apache.log4j.FileAppender &quot;> <param name=&quot; File &quot; value=&quot;/log/myFile.log&quot; /> <param name=&quot; Append &quot; value=&quot;true&quot; /> <param name=&quot; Threshold &quot; value=&quot;INFO&quot;/> . . . </appender> FileAppenders: Appends log events to a file. File : path and filename of the file. Append : If true, open the file in append mode. If false, open in truncate mode. Threshold : Set the threshold level. All log events with lower level than the threshold level are ignored by the appender. (TRACE, DEBUG, INFO, WARN, ERROR and FATAL) ImmediateFlush : Default is true, meaning log messages are not buffered at all which is what you want almost all of the time.
  • <appender name=&quot;RollingFileSample&quot; class=&quot; org.apache.log4j.RollingFileAppender &quot;> <param name=&quot;File&quot; value=&quot;/log/myRollingFile.log&quot;/> <param name=&quot;Append&quot; value=&quot;true&quot;/> <param name=&quot; MaxFileSize &quot; value=&quot;500KB&quot;/> <param name=&quot; MaxBackupIndex &quot; value=&quot;1&quot;/> . . . </appender> RollingFileAppenders: Extends FileAppender to backup the log files when they reach a certain size . MaxFileSize : Set the maximum size that the output file is allowed to reach before being rolled over to backup files. You can specify the value with the suffixes &quot;KB&quot;,&quot;MB&quot; or &quot;GB“. MaxBackupIndex : Set the maximum number of backup files to keep around. 0 means no backup files at all. * Plus all parameters from fileAppender
  • <appender name=&quot;DRFileSample&quot; class=&quot; org.apache.log4j.DailyRollingFileAppender &quot;> <param name=&quot;File&quot; value=&quot;/log/myDailyFile.log&quot;/> <param name=&quot;DatePattern&quot; value=&quot;'.'yyyy-MM-dd'.log'&quot;/> <layout class=&quot;org.apache.log4j.PatternLayout&quot;> <param name=&quot;ConversionPattern&quot; value=&quot;%d %-5p [%c] %m%n&quot;/> </layout> </appender> DailyRollingFileAppender: Extends FileAppender so that the underlying file is rolled over at a user chosen frequency. DatePattern : Takes a string in the same format as expected by SimpleDateFormat . This options determines the rollover schedule. Ex: DatePattern Rollover schedule '.'yyyy-MM' Rollover at the beginning of each month '.'yyyy-MM-dd' Rollover at midnight each day. '.'yyyy-MM-dd-HH' Rollover at the top of every hour. where '.' represent your filename in the datePattern * Plus all parameters from fileAppender
  • <appender name=&quot;CONSOLE&quot; class=&quot; org.apache.log4j.ConsoleAppender &quot;> <param name=&quot; Target &quot; value=&quot;System.out&quot;/> <param name=&quot; Threshold &quot; value=&quot;INFO&quot;/> . . . </appender> ConsoleAppender: appends log events to System.out or System.err using a layout specified by the user. The default target is System.out. Target : Recognized values are &quot;System.out&quot; and &quot;System.err&quot;. Any other value will be ignored. Threshold : TRACE, DEBUG, INFO, WARN, ERROR and FATAL. ImmediateFlush : Default is true, meaning log messages are not buffered at all which is what you want almost all of the time.
  • <appender name=&quot;JDBCSample&quot; class=&quot; org.apache.log4j.jdbc.JDBCAppender &quot;> <param name=&quot; Threshold &quot; value=&quot;ERROR&quot;/> <param name=&quot; driver &quot; value=&quot;com.sybase.jdbc2.jdbc.SybDriver&quot;/> <param name=&quot; URL &quot; value=&quot;jdbc:sybase:Tds:127.0.0.1:2638/Summit&quot;/> <param name=&quot; user &quot; value=&quot;DBA&quot;/> <param name=&quot; password &quot; value=&quot;SQL&quot;/> . . . </appender> JDBCAppender: sending log events to a database. Driver : Ensures that the given driver class has been loaded for SQL connection creation. URL : url / jdbc connection. user : Connection username. password : Connection username. Threshold : TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
  • <appender name=&quot;EmailSample&quot; class=&quot; org.apache.log4j.net.SMTPAppender &quot;> <param name=&quot; Threshold &quot; value=&quot;FATAL&quot;/> <param name=&quot; To &quot; value=&quot;name@email.com&quot;/> <param name=&quot; From &quot; value=&quot;name@email.com&quot;/> <param name=&quot; Subject &quot; value=&quot;One Fatal Error&quot;/> <param name=&quot; SMTPHost &quot; value=&quot;localhost&quot;/> <param name=&quot; BufferSize &quot; value=&quot;10&quot;/> . . . </appender> SMTPAppender: Send an e-mail when a specific logging event occurs. To, From : takes a string value which should be a comma separated list of e-mail address of the recipients / sender. Cc, Bcc : the cc and bcc recipient addresses. Subject : the subject of the e-mail message. SMTHHost : the host name of the SMTP server that will send the e-mail message. SMTHUsername : the username required to authenticate against the mail server. SMTHPassword : the password required to authenticate against the mail server. BufferSize : the maximum number of logging events to collect in a cyclic buffer. Threshold : TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
  • Agenda
    • Definition
    • Basic features
    • Level
    • Appenders
    • Loggers
    • Layouts
    • Filters
    • Tips
  • Loggers
    • Now the appenders are configured. But how to configure loggers to output messages at a certain level? How to configure loggers to output to specific appender? Welcome to logger configuration. The most important logger you need to configure is the root logger. From the simple example, this was done with the following configuration:
    <root> <priority value =&quot;debug&quot; /> <appender-ref ref=&quot;console&quot; /> </root> The root logger is configured to output log message at level &quot;debug&quot; or higher to the appender named &quot;console&quot;. All loggers inherit their settings from the root logger, so with no other configuration settings, all loggers will output all of their messages to the &quot;console&quot; appender automatically. This may be fine for simple debugging, but eventually more specific logger configuration is going to be required.
    • A logger element must have a name attribute. This is the name of the logger used when creating the Logger instance(usually the fully qualified class name).
    • A logger element can also contain child elements:
      • 0 or 1 level element - This defines the level of log messages that will be allowed to be logged for this logger. Normal usage has a value of &quot;debug&quot;, &quot;info&quot;, &quot;warn&quot;, &quot;error&quot;, or &quot;fatal&quot;. Only that level or above will be reported to the log.
      • 0 or more appender-ref elements - This references a defined appender that log messages from this logger should be directed to. Appender-ref elements are simple elements that have a ref attribute. The value for this attribute should be the name of the appender.
    <!ELEMENT logger (level?,appender-ref*)> <!ATTLIST logger name ID #REQUIRED additivity (true|false) &quot;true&quot; > log4j.dtd
    • The logger is configured to output log message at level “info&quot; or higher to the default appender Root , cause there’s no appender-ref defined. And the logger will log message coming from the specific class com.mycompany.apackage.MyClass .
    • You can log for a entire package by changing the name to com.mycompany.apackage . And every message coming from the package com.mycompany.apackage , will be log.
    <logger name=&quot;com.mycompany.apackage.MyClass&quot;> <level value=&quot;info&quot;/> </logger> A simple example
  • Agenda
    • Definition
    • Basic features
    • Level
    • Appenders
    • Loggers
    • Layouts
    • Filters
    • Tips
  • Layouts
    • Method of customizing output from logger: Simple, HTML, Pattern and XML layouts are included
    • Some layout classes are SimpleLayout, PatternLayout, HTMLLayout, and XMLLayout.
    • Custom object renderers can be installed
    SimpleLayout - org.apache.log4j.SimpleLayout SimpleLayout consists of the priority of the log statement, followed by &quot; - &quot; and then the log message itself. For example: DEBUG - Hello world <!ELEMENT layout (param*)> <!ATTLIST layout class CDATA #REQUIRED > log4j.dtd
  • PatternLayout - org.apache.log4j.PatternLayout
    • PatternLayout lets you specify the output format according to conversion patterns similar to the C language printf function.
    • For example , PatternLayout with the conversion pattern %r [%t] %-5p %c - %m%n will output something like:
    • 176 [main] INFO org.foo.Bar - Located nearest gas station.
      • The first field is the number of milliseconds elapsed since the start of the program.
      • The second field is the thread making the log request.
      • The third field is the priority of the log statement.
      • The fourth field is the name of the category associated with the log request.
      • The text after the '-' is the message of the statement.
    • You can insert any literal text within the conversion pattern
    • Conversion characters are:
      • %m: Outputs your message.
      • %p: Outputs the priority of the logging event.
      • %r: Outputs the number of milliseconds elapsed since the start of the application until the creation of the logging event.
      • %c: Outputs the category of the logging event. Example: For the category name &quot;a.b.c&quot;, the pattern %c{2} will output &quot;b.c&quot;. {2} means &quot;output last two components of the dot-separated category name&quot;. If no {n} is there, full Category name is output by default.
      • %t: Outputs the name of the thread that generated the logging event.
      • %x: Outputs the nested diagnostic context (NDC) associated with the thread that generated the logging event. Useful when multiple clients are handled by separate threads such as in Java servlets.
    • Conversion characters are (Continue…):
      • %n: Outputs the platform-dependent newline character(s). Preferable to specifying &quot;n&quot; or &quot;rn&quot; etc.
      • %%: Outputs a single percent sign.
      • WARNING : The patterns below will slow down the execution of your program somewhat. Avoid unless execution speed is not an issue.
      • %d: Outputs the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. 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 Java's SimpleDateFormat which is slow. For faster performance, use %d{ISO8601}, %d{ABSOLUTE}, %d{RELATIVE} (millisecs since program start, fastest) or %d{DATE} which use log4j's ISO8601DateFormat, AbsoluteTimeDateFormat, RelativeTimeDateFormat and DateTimeDateFormat date formatters respectively.
    • Conversion characters are (Continue…):
      • %l: Outputs source code location information. Shortcut for %C.%M(%F:%L).
      • %C: Outputs the fully-qualified class name of the caller issuing the logging request. Example: For the class name &quot;org.apache.xyz.SomeClass&quot;, the pattern %C{1} will output &quot;SomeClass&quot;. {1} means &quot;output last one component of the fully-qualified class name&quot;. If no {n} is there, full class name is output by default.
      • %M: Outputs the method name where the logging request was issued.
      • %F: Outputs the file name where the logging request was issued.
      • %L: Outputs the line number from where the logging request was issued.
      • -: To left-justify within a field. Default is to right-justify (pad on left).
    • Pattern:
    • %d{dd MM yyyy HH:mm:ss} %p %l: %m %n
    • This example will output:
    • %d{dd MM yyyy HH:mm:ss} : 07 12 2006 09:25:02 (Date)
    • %p: ERROR (Priority)
    • %l: com.ing.canada.YourClass.yourMethod(filename.java:65) ( source code location)
    • %m: TEST ERROR (message)
    • %n: (newline character)
    PatternLayout - Example
  • XMLLayout - org.apache.log4j.xml.XMLLayout The output of the XMLLayout consists of a series of log4j:event elements as defined in the log4j.dtd. It does not output a complete well-formed XML file. The output is designed to be included as an external entity in a separate file to form a correct XML file. For example, if abc is the name of the faile where the XMLLayout output goes, then a well-formed XML file would be: <log4j:event logger=&quot;com.ing.canada.myPackage.MyClass&quot; timestamp=&quot;1165519924224&quot; level=&quot;FATAL&quot; thread=&quot;Servlet.Engine.Transports : 0&quot;> <log4j:message> <![CDATA[TEST FATAL. debug]]> </log4j:message> </log4j:event>
  • HTMLLayout - org.apache.log4j.HTMLLayout This layout outputs events in a HTML table. <body bgcolor=&quot;#FFFFFF&quot; topmargin=&quot;6&quot; leftmargin=&quot;6&quot;> <hr size=&quot;1&quot; noshade> Log session start time Thu Dec 07 15:03:00 EST 2006<br><br> <table cellspacing=&quot;0&quot; cellpadding=&quot;4&quot; border=&quot;1&quot; bordercolor=&quot;#224466&quot; width=&quot;100%&quot;> <tr> <th>Time</th><th>Thread</th><th>Level</th><th>Category</th> <th>File:Line</th><th>Message</th> </tr> <tr> <td>16</td> <td title=&quot;Servlet.Engine.Transports : 0 thread&quot;>Servlet.Engine.Transports : 0</td> <td title=&quot;Level&quot;><font color=&quot;#993300&quot;><strong>FATAL</strong></font></td> <td title=&quot;com.ing.canada.autoquote.filter.SessionAttributesFiltercategory&quot;> com.ing.canada.autoquote.filter.SessionAttributesFilter </td> <td>SessionAttributesFilter.java:66</td> <td title=&quot;Message&quot;>TEST FATAL. debug</td> </tr>
  • Layout Configuration Example <layout class=&quot;org.apache.log4j. PatternLayout &quot;> <param name=&quot; ConversionPattern &quot; value=&quot;%d %-5p [%c] %m%n&quot;/> </layout> <layout class=&quot;org.apache.log4j.xml. XMLLayout &quot;> <param name=&quot; LocationInfo &quot; value=&quot;true&quot; /> </layout> <layout class=&quot;org.apache.log4j. HTMLLayout &quot;> <param name=&quot;LocationInfo&quot; value=&quot;true&quot; /> <param name=&quot; Title &quot; value=“Html Title&quot; /> </layout> ConvesionPattern : This is the string which controls formatting and consists of a mix of literal content and conversion specifiers. LocationInfo : If the the option is set to true, then the file name and line number of the statement at the origin of the log statement will be output. Default is false. Title : This option sets the document title of the generated HTML document.
  • Agenda
    • Definition
    • Basic features
    • Level
    • Appenders
    • Loggers
    • Layouts
    • Filters
    • Tips
  • Filters
    • At some situation, You have to write logs to different outputs according to the level. How can it be done by simply configuration of Log4j?
    • By using LevelMatchFilter, LevelRangeFilter or StringMatchFilter .
    • You can define multiple filter for the same appender.
      • But Keep in mind that when attaching multiple filters to the same appender, that if the statement fails one filter, it will pass down to the next . A denial by a filter does not necessarily mean that the message is thrown away. The message just fails that filter and goes onto the next one (except in the case of DenyAllFilter). Which is why it's always safest to have a &quot;DenyAllFilter&quot; at the bottom of the list to catch the stragglers.
    • Notes : Filter is not supported by PropertiesConfigurator , so if you want to configure it, just use the XML file instead.
  • LevelMatchFilter The filter admits two options LevelToMatch and AcceptOnMatch. LevelToMatch: TRACE, DEBUG, INFO, WARN, ERROR or FATAL AcceptOnMatch: If acceptOnMatch is set to true (default) and the level match the criteria all others filters will not be execute and the message will be accepted. Otherwise the message is rejected and passed to the next filter. <filter class=&quot; org.apache.log4j.varia.LevelMatchFilter &quot;> <param name=&quot; LevelToMatch &quot; value=&quot;INFO&quot;/> <param name=&quot; AcceptOnMatch &quot; value=&quot;true&quot;/> </filter> Filter based on level matching .
  • LevelRangeFilter The filter admits three options LevelMin, LevelMax and AcceptOnMatch. LevelMin: TRACE, DEBUG, INFO, WARN, ERROR or FATAL LevelMin: TRACE, DEBUG, INFO, WARN, ERROR or FATAL AcceptOnMatch: If acceptOnMatch is set to true (default) and the level match the criteria all others filters will not be execute and the message will be accepted. Otherwise the message is rejected and passed to the next filter. <filter class=&quot; org.apache.log4j.varia.LevelRangeFilter &quot;> <param name=&quot; LevelMin &quot; value=&quot;DEBUG&quot;/> <param name=&quot; LevelMax &quot; value=&quot;ERROR&quot;/> <param name=&quot; AcceptOnMatch &quot; value=&quot;true&quot;/> </filter> Filter based on level matching, which can be used to reject messages with priorities outside a certain range (inclusive).
  • StringMatchFilter The filter admits two options StringToMatch and AcceptOnMatch. StringToMatch: String to find in the message AcceptOnMatch: If acceptOnMatch is set to true (default) and the level match the criteria all others filters will not be execute and the message will be accepted. Otherwise the message is rejected and passed to the next filter. <filter class=&quot; org.apache.log4j.varia.StringMatchFilter &quot;> <param name=&quot; StringToMatch &quot; value=&quot;1&quot; /> <param name=&quot; AcceptOnMatch &quot; value=&quot;true&quot; /> </filter> Filter based on string matching (Case sensitive) .
  • DenyAllFilter You can add this filter to the end of a filter chain to switch from the default &quot;accept all unless instructed otherwise&quot; filtering behaviour to a &quot;deny all unless instructed otherwise&quot; behaviour. <filter class=&quot; org.apache.log4j.varia.DenyAllFilter &quot;/> This filter drops all logging events.
  • Log4j.xml
    • Debug : Probably the most important attribute for log4:configuration, setting it to &quot;true&quot; will print out information as the configuration file is read and used to configure the log4j environment. Very useful when trying to figure out why your configuration file is not doing what you expect.
    • Threshold : Set to off to disable all logging.
    <!ELEMENT appender (errorHandler?, param*, layout?, filter*, appender-ref*)> <!ATTLIST log4j:configuration xmlns:log4j CDATA #FIXED &quot;http://jakarta.apache.org/log4j/&quot; threshold (all|debug|info|warn|error|fatal|off|null) &quot;null“ debug (true|false|null) &quot;null&quot; >
  • Agenda
    • Definition
    • Basic features
    • Level
    • Appenders
    • Loggers
    • Layouts
    • Filters
    • Tips
    • When the generation of your logging message takes a long time, you might want to check to see if it will ever make it to an appender Functions like isDebugEnabled() and isEnabledFor() on the Logger class allow you to test first (testing is very fast) and then generate the string and log it if you know the message will actually be logged.
    • You can use system properties in the log4j.xml by simply call ${VAR_NAME}. You can now configure runtime information like path/filename without changing your configuration file.
    Tips