‏הצגת רשומות עם תוויות log4j. הצג את כל הרשומות
‏הצגת רשומות עם תוויות log4j. הצג את כל הרשומות

יום שישי, 25 באפריל 2014

Logging element in the Camel route

Adding logging element to the Camel route is very simple (By all mean).
The following code adds a logging element to the cxfrs route :

@Override
public void configure() throws Exception {   	
	from(uri)
		.log(LoggingLevel.INFO , "the body ${body} and the operation ${in.header[" + CxfConstants.OPERATION_NAME +"]}")
		.process(new Processor() {
		public void process(Exchange exchange) throws Exception { 

The syntax in the demo of the log template is based on Camel Simple Expression Language.
And the result after calling :
http://localhost:8080/camel-example-cxfrs-tomcat/webservices/myData/RsService/SayHello/Mazal-saadon
Is:

2014-04-25 13:38:47,782 [bio-8080-exec-4] INFO  route1                         - the body Mazal-saadon and the operation SayHello

Add Debugging logging and tracing to my Camel cxfrs rest server

In order to debug the camel routes and find why there problem transferring or processing messages there is an option to set tracing on camel .

Adding tracing to the camel-config.Xml file :

<bean id="camelTracer" class="org.apache.camel.processor.interceptor.Tracer">
    <property name="traceExceptions" value="true"/>
    <property name="traceInterceptors" value="true"/>
    <property name="logLevel" value="INFO"/>
    <property name="logName" value="com.mycompany.messages"/>
</bean>
  
<camelContext xmlns="http://camel.apache.org/schema/spring" trace="true">

Add to the log4j configuration file appender in order to make the log more readably


log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\Temp\\loging.txt
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n

In the route builder in the configure method we can call to set the logging output formatting:


 @Override
    public void configure() throws Exception {   
        
        Tracer tracer = new Tracer();
        tracer.setTraceOutExchanges(true);
        // we configure the default trace formatter where we can
        // specify which fields we want in the output
        DefaultTraceFormatter formatter = new DefaultTraceFormatter();
        formatter.setShowOutBody(true);
        formatter.setShowOutBodyType(true);
        formatter.setShowException(true);
        formatter.setShowExchangePattern(true);
        formatter.setShowProperties(true);
        formatter.setShowOutHeaders(true);
        // set to use our formatter
        tracer.setFormatter(formatter);
        getContext().addInterceptStrategy(tracer);
.
.
.
.


The logging information is dump to both the tomcat server console log and to the log file that has bean declared in the log4j configuration file :
2014-04-25 11:46:28,576 [io-8080-exec-42] INFO  messages                       - ID-Zvika-PC-2757-1398415530094-0-14 >>> (route2) wireTap(Endpoint[seda://tap]) --> org.apache.camel.example.cxf.CamelRoute$1@1a304efc <<< Pattern:InOut, Headers:{breadcrumbId=ID-Zvika-PC-2757-1398415530094-0-13, connection=Keep-Alive, user-agent=Apache-HttpClient/4.1.1 (java 1.5), CamelCxfRsResponseGenericType=class javax.ws.rs.core.Response, CamelCxfRsOperationResourceInfoStack=[org.apache.cxf.jaxrs.model.MethodInvocationInfo@6b6e21bb], CamelAcceptContentType=*/*, CamelCxfMessage=org.apache.cxf.message.XMLMessage@99357e13, operationName=SayHello, CamelCxfRsResponseClass=class javax.ws.rs.core.Response, Name=EtiGoldfarb, CamelHttpPath=/RsService/SayHello/EtiGoldfarb, accept-encoding=gzip,deflate, CamelHttpMethod=GET, host=localhost:8080, CamelHttpUri=/camel-example-cxfrs-tomcat/webservices/myData/RsService/SayHello/EtiGoldfarb}, BodyType:org.apache.cxf.message.MessageContentsList, Body:EtiGoldfarb
2014-04-25 11:46:28,578 [#0 - seda://tap] INFO  messages                       - ID-Zvika-PC-2757-1398415530094-0-16 >>> (route1) from(seda://tap) --> log[the body ${body}] <<< Pattern:InOnly, Headers:{CamelHttpUri=/camel-example-cxfrs-tomcat/webservices/myData/RsService/SayHello/EtiGoldfarb, CamelHttpPath=/RsService/SayHello/EtiGoldfarb, host=localhost:8080, CamelAcceptContentType=*/*, operationName=SayHello, CamelCxfRsResponseGenericType=class javax.ws.rs.core.Response, breadcrumbId=ID-Zvika-PC-2757-1398415530094-0-13, CamelCxfRsResponseClass=class javax.ws.rs.core.Response, connection=Keep-Alive, accept-encoding=gzip,deflate, CamelCxfRsOperationResourceInfoStack=[org.apache.cxf.jaxrs.model.MethodInvocationInfo@6b6e21bb], CamelHttpMethod=GET, Name=EtiGoldfarb, user-agent=Apache-HttpClient/4.1.1 (java 1.5),
CamelCxfMessage=org.apache.cxf.message.XMLMessage@99357e13}, BodyType:org.apache.cxf.message.MessageContentsList, Body:EtiGoldfarb

Example for detailed exception in the log :
org.apache.camel.RuntimeCamelException: org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >>> From[seda:tap2] <<< in route: Route(route1)[[From[seda:tap2]] -> []] because of Route route1 has no output processors. You need to add outputs to the route such as to("log:foo").

יום שבת, 1 ביוני 2013

Simple logging with log4j

Getting the log4j jars using maven
The pom file

  1: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2:   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3:   <modelVersion>4.0.0</modelVersion>
  4: 
  5:   <groupId>com.mycompany</groupId>
  6:   <artifactId>Log4jTest</artifactId>
  7:   <version>1.0-SNAPSHOT</version>
  8:   <packaging>jar</packaging>
  9:   <name>Log4jTest</name>
 10:   <url>http://maven.apache.org</url>
 11: 
 12:   <properties>
 13:     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 14:   </properties>
 15: 
 16:   <dependencies>
 17:    
 18:   <dependency>
 19:   <groupId>log4j</groupId>
 20:   <artifactId>log4j</artifactId>
 21:   <version>1.2.17</version>
 22:     </dependency>  
 23:   </dependencies>
 24: </project>
 25: 

The log4j configuration file.
Note: 2 appeanders are declared one for the output of logging into the console and one for output it to file.  
The appeanders to use in each call to logging are declared 


  1: <?xml version="1.0" encoding="UTF-8" ?>
  2: <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  3: <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
  4: 
  5:     <appender name="default.file" class="org.apache.log4j.FileAppender">
  6:         <param name="file" value="/log/mylogfile.log" />
  7:          <param name="append" value="false" />
  8:         <param name="threshold" value="debug" />
  9:         <layout class="org.apache.log4j.PatternLayout">
 10:             <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
 11:         </layout>
 12:     </appender>
 13: 
 14:     <appender name="default.console" class="org.apache.log4j.ConsoleAppender">
 15:         <param name="target" value="System.out" />
 16:         <param name="threshold" value="debug" />
 17:         <layout class="org.apache.log4j.PatternLayout">
 18:             <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
 19:         </layout>
 20:     </appender>
 21:   
 22:     <root>
 23:       <priority value="info" />
 24:       <appender-ref ref="default.file" />      
 25:     <appender-ref ref="default.console" />
 26:       
 27:     </root>
 28: </log4j:configuration>

The main file
The main file the demonstarts the use of logging.
Note about the configuration laoding using the DomConfigurator object


  1: package com.mycompany.log4jtest;
  2: 
  3: import org.apache.log4j.LogManager;
  4: import org.apache.log4j.Logger;
  5: import org.apache.log4j.xml.DOMConfigurator;
  6: 
  7: public class App 
  8: {
  9:     private static Logger logger = LogManager.getLogger("myLogger");
 10:   
 11:     public static void main( String[] args )
 12:     {
 13:         DOMConfigurator.configure("log4j.xml");
 14:         logger.info("This is an info!");
 15:         logger.error("This is an error!");
 16:         System.out.println( "Done!" );
 17:     }
 18: }
 19: 

The output
------------------------------------------------------------------------
Building Log4jTest 1.0-SNAPSHOT
------------------------------------------------------------------------


[resources:resources]
[debug] execute contextualize
Using 'UTF-8' encoding to copy filtered resources.
skip non existing resourceDirectory I:\Learn\java\Log4jTest\src\main\resources


[compiler:compile]
Compiling 1 source file to I:\Learn\java\Log4jTest\target\classes


[exec:exec]
2013-06-01 22:48:06,945 INFO  [myLogger] - This is an info!
2013-06-01 22:48:06,946 ERROR [myLogger] - This is an error!
Done!
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.313s
Finished at: Sat Jun 01 22:48:06 IDT 2013
Final Memory: 6M/15M
------------------------------------------------------------------------


sources
http://stackoverflow.com/questions/6358836/log4j-how-to-configure-simplest-possible-file-logging
http://www.dzone.com/tutorials/java/log4j/log4j-file-appender-example-1.html