Configure Wiremock to use log4j with a Custom Transformer - java

I'm running Wiremock as a Standalone process (v2.5.1). I've created a Java custom transformer by extending: com.github.tomakehurst.wiremock.extension.ResponseTransformer
My custom transformer then uses some other common code that uses Log4J for logging. With code like:
import org.apache.log4j.Logger;
private static Logger logger = Logger.getLogger(CommonCode.class);
...
logger.error("This is some error");
Is there anyway I can configure Wiremock to output this custom logging? I've tried putting a log4j.xml and log4j.properties file in the classpath. Here's an example of a properties file:
log4j.appender.CUSTOMAPPENDER=org.apache.log4j.RollingFileAppender
log4j.appender.CUSTOMAPPENDER.File=c:/WireMock/logs/custom.log
log4j.appender.CUSTOMAPPENDER.layout=org.apache.log4j.PatternLayout
log4j.logger.com.myorg=DEBUG, CUSTOMAPPENDER
The equivalent log4j.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="CUSTOMAPPENDER" class="org.apache.log4j.DailyRollingFileAppender">
<param name="file" value="C:/WireMock/logs/custom.log"/>
<param name="datePattern" value="'.'yyyy-MM-dd"/>
<param name="append" value="true"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{MMM dd HH:mm:ss}] [%r] %5p [%t] (%F:%L) - %m%n"/>
</layout>
</appender>
<logger name="com.myorg" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="CUSTOMAPPENDER"/>
</logger>
</log4j:configuration>
I also have the following JARs in my classpath:
log4j-1.2.17.jar
slf4j-api-1.7.2.jar
slf4j-log4j12-1.7.2.jar
I'd like this custom logging to go to a separate log file from the Default Wiremock verbose logging. Any help would be appreciated.

Once I realised it was simply that log4j could not find the log4j.properties or log4j.xml file I was able to resolve the issue. Basically the log4j properties file must be in the classpath for the Wiremock Java process.
I was running the Wiremock Server via a batch script which looked like this:
"C:/Java/jdk1.8.0_102/bin/java" -Dfile.encoding=UTF-8 -cp "C:/WireMock/lib/wiremock-standalone-2.5.1.jar;C:/WireMock/lib/*" com.github.tomakehurst.wiremock.standalone.WireMockServerRunner --port="9091" --extensions "com.myorg.CustomTransformer" --root-dir="C:/WireMock" --verbose > "C:/WireMock/logs/wiremock.log"
My log4j.xml file was in my C:/WireMock/lib directory. I assumed that because I had a classpath entry of cp "C:/WireMock/lib/wiremock-standalone-2.5.1.jar;C:/WireMock/lib/*" which included C:/WireMock/lib/* that it would pick up my log4j properties. I also explicitly added the properties file to this classpath. Neither of these worked (hence this question). My Custom transformer class com.myorg.CustomTransformer is present in a jar also in the lib directory (which is picked up).
However after some research I found 2 ways to get the log4j properties file to be picked up.
Specify the log4j properties location as another -D parameter in the batch script. If I added -Dlog4j.configuration=file://c:/WireMock/lib/log4j.xml
Update my custom jar build script to include the log4j.xml file itself in the jar.

Related

JAVA: Configure logback in standalone apps

I have a Java standalone app. with a main method, with these 2 imports:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
and
private static final Logger log = LoggerFactory.getLogger(PecadorDeLaPradera.class);
In the same folder I also have a logback.xml but I don't know how to tell the program that uses the logback.xml to config the log
I couldn't find any class similar to org.apache.log4j.PropertyConfigurator
I have this logback.xml in the same folder of the Java class I am running:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- trace, debug, info, warn, error, fatal -->
<timestamp key="myTimestamp" datePattern="yyyy-MM-dd'_'HH-mm-ss.SSS"/>
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL>
</contextListener>
<!-- To enable JMX Management -->
<jmxConfigurator/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{"yyyy-MM-dd HH:mm"} [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>pecador.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>handler.%i.log.zip</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>3</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>1MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{"yyyy-MM-dd HH:mm"} [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<!-- <logger name="org.springframework.orm.jpa" level="debug" /> -->
<logger name="com.calzada.pecador" level="debug" />
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
</configuration>
I also run the appl. with Program arguments:
-Dlogback.configurationFile=/Users/calzada/Dev/J2EE/eclipseWSJ2EE/myApp/src/com/calzada/pecador/logback.xml
and I got this error:
java.util.MissingResourceException: Can't find bundle for base name -Dlogback.configurationFile=/Users/nullpointer/Development/J2EE/eclipseWSJ2EE/myApp/src/com/calzada/pecador/logback.xml, locale en_ES
The library used is logback-classic-1.2.3.jar
Here's how logback configures itself:
Logback tries to find a file called logback-test.xml in the classpath.
If no such file is found, logback tries to find a file called logback.groovy in the classpath.
If no such file is found, it checks for the file logback.xml in the classpath.
If no such file is found, service-provider loading facility (introduced in JDK 1.6) is used to resolve the implementation of com.qos.logback.classic.spi.Configurator interface by looking up the file META-INF\services\ch.qos.logback.classic.spi.Configurator in the class path. Its contents should specify the fully qualified class name of the desired Configurator implementation.
If none of the above succeeds, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.
You can also point Logback at a specific configuration file using the system parameter logback.configurationFile. From the docs:
You may specify the location of the default configuration file with a system property named "logback.configurationFile". The value of this property can be a URL, a resource on the class path or a path to a file external to the application.
java -Dlogback.configurationFile=/path/to/config.xml chapters.configuration.MyApp1
All the above taken from the docs.
According to your question you have a logback.xml but this file is in the "same folder" as your class. Unless your class is in the root package this means that logback.xml is not in the root of the classpath so Logback will not discover it. In order for Logback to configure itself from this file you can do one of the following:
Place your logback.xml in the root of your classpath (for a Maven project this is as simple as copying logback.xml to src/main/resources)
Run your Java program with -Dlogback.configurationFile=/path/to/logback.xml

System.out.println not printing to console

I have a Spring web app running on Wildfly 8.* and for some reason it won't print to the console. I see all the console logs and stack traces fine but the System messages just don't appear.
The problem might be with my log4j setup so I'll post that config;
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration PUBLIC
"-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration debug="true"
xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="console" />
</root>
</log4j:configuration>
I've ran apps on JBoss 7.1 before however without this problem so I'm really at a loss on what could be wrong.
Feel free to ask about any of my other config not sure what would be needed.
Edit:
logger.org.jboss.as.config.level=DEBUG
logger.org.jboss.as.config.useParentHandlers=true
logger.jacorb.config.level=ERROR
logger.jacorb.config.useParentHandlers=true
logger.org.apache.tomcat.util.modeler.level=WARN
logger.org.apache.tomcat.util.modeler.useParentHandlers=true
logger.com.arjuna.level=WARN
logger.com.arjuna.useParentHandlers=true
handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
handler.CONSOLE.level=INFO
handler.CONSOLE.formatter=COLOR-PATTERN
handler.CONSOLE.properties=autoFlush,target,enabled
handler.CONSOLE.autoFlush=true
handler.CONSOLE.target=SYSTEM_OUT
handler.CONSOLE.enabled=true
handler.FILE=org.jboss.logmanager.handlers.PeriodicRotatingFileHandler
handler.FILE.level=ALL
handler.FILE.formatter=PATTERN
handler.FILE.properties=append,autoFlush,enabled,suffix,fileName
handler.FILE.constructorProperties=fileName,append
handler.FILE.append=true
handler.FILE.autoFlush=true
handler.FILE.enabled=true
handler.FILE.suffix=.yyyy-MM-dd
handler.FILE.fileName=C\:\\wildfly-8.2.0.Final\\standalone\\log\\server.log
formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
formatter.PATTERN.properties=pattern
formatter.PATTERN.pattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} %-5p [%c] (%t) %s%E%n
formatter.COLOR-PATTERN=org.jboss.logmanager.formatters.PatternFormatter
formatter.COLOR-PATTERN.properties=pattern
formatter.COLOR-PATTERN.pattern=%K{level}%d{HH\:mm\:ss,SSS} %-5p [%c] (%t) %s%E%n
Here is my logging config in my standalone deployments folder.
I had a log4j.properties file at the root level of the .war (WEB-INF/classes) from years ago that caused the same issue - deletion fixed it
Since you are using a logging framework, there are 2 ways to fix it:
Remove the logging framework and all the configuration files (why would I do that)
Move your log4j.properties file from src/main/resources to WEB-INF folder.
Quoting: JBoss Docs, Section 'Per Deployment Logging'
Per-deployment logging allows you to add a logging configuration file to your deployment and have the logging for that deployment configured according to the configuration file. In an EAR the configuration should be in the META-INF directory. In a WAR or JAR deployment the configuration file can be in either the META-INF or WEB-INF/classes directories.
The following configuration files are allowed:
logging.properties
jboss-logging.properties
log4j.properties
log4j.xml
jboss-log4j.xml
I usually have trouble configuring logs per deployment in wildfly, but you can use the logging system from wildfly, changing logging configuration of your standalone ou domain config files to this would do the trick:
<root-logger>
<level name="TRACE"/>
<handlers>
<handler name="CONSOLE"/>
<handler name="FILE"/>
</handlers>
</root-logger>

unable to find logback.xml

I'm trying to use logback as my logger in my simple program but it does not work fine!
I put logback/logback.xml and logback/Logback.java in the source directory logback and run through this command line
\logback>java -cp .;%CLASSPATH% Logback
which the %CLASSPATH% is an environment variable that has the path of .jar file that logback needs like:
logback-access-1.1.2.jar
logback-classic-1.1.2.jar
logback-core-1.1.2.jar
slf4j-api-1.7.6.jar
This is my logback.xml file
<configuration>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>test.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>tests.%i.log</fileNamePattern>
<minIndex>1</minIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>2MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration>
and there is my simple program
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Logback{
private final static Logger logger = LoggerFactory.getLogger(Logback.class);
public static void main(String[] args){
for(int i=0;i<1000000;i++)
logger.debug("hello");
}
}
but unfortunately i just receive log in the console instead of test.log files. it seems the logger object just use the default configuration!!!
If i set the -Dlogback.configurationFile=logback.xml variable as below, it works properly. but how to run without this variable?
\logback>java -cp .;%CLASSPATH% -Dlogback.configurationFile=logback.xml Logback
From logback documentation:
1. Logback tries to find a file called logback.groovy in the classpath.
2. If no such file is found, logback tries to find a file called logback-test.xml in the classpath.
3. If no such file is found, it checks for the file logback.xml in the classpath..
4. If neither file is found, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.
Where should the configuration files such as logback.groovy, logback-test.xml or logback.xml be located on the classpath?
Configuration files such as logback.groovy, logback-test.xml or logback.xml can be located directly under any folder declared in the class path. For example, if the class path reads "c:/java/jdk15/lib/rt.jar;c:/mylibs/" then the logback.xml file should be located directly under "c:/mylibs/", that is as "c:/mylibs/logback.xml". Placing it under a sub-folder of c:/mylibs/, say, c:/mylibs/other/, will not work.
For web-applications, configuration files can be placed directly under WEB-INF/classes/.
So you need to put logback.xml in the classpath. On one project we had a similar problem although logback.xml was in the right place. Renaming it to logback-test.xml helped.
If you add the jar files to C:\Program Files\Java\jre7\lib\ext . and try to run the program like below:
\logback>java Logback
it wont see the logback.xml file in the source directory
when i deleted the
logback-access-1.1.2.jar
logback-classic-1.1.2.jar
logback-core-1.1.2.jar
slf4j-api-1.7.6.jar
files from C:\Program Files\Java\jre7\lib\ext, it went OK!

How to Step By Step configure logging in jboss 6.x with Log4j in Java

Hi all I am new to Jboss so I am get confused while setting up an logging in Jboss 6.1 what I does
I have download and extract the Jboss (jboss-eap-6.1) on my machine then I follow the steps given in this article but still I not able to see the logging on console or in file
the I google it around and come to know that I have to write jboss-deployment-structure.xml file under /META-INF/ folder and have to add -Dorg.jboss.as.logging.per-deployment=false to the start-up of the server (which I dont know where I have to set this) from this link
so can any one give me steps to configure logging in jboss 6.x with Log4j or any logging like java.util.logging to log statements on console or in file thanks.
You should find the standalone.bat file into the /bin folder of Jboss, then you should edit this file, finding the next line
rem Setup JBoss specific properties
set JAVA_OPTS=-Dprogram.‌​name=%PROGNAME% %JAVA_OPTS%
And replace for this
set "JAVA_OPTS= -Dorg.jboss.as.logging.per-deployment=false"
If you want logging
a. you want to use your own "log4j.jar" place it in lib folder
b. place jboss-deployment-structure.xml in META-INF folder
c. Add log4j.xml in WEB-INF/classes
of your application.
Add this in jboss-deployment-structure.xml
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
<deployment>
<exclusions>
<module name="org.apache.log4j" />
</exclusions>
</deployment>
</jboss-deployment-structure>
Add this in log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="appender" class="org.apache.log4j.FileAppender">
<param name="File" value="${jboss.server.log.dir}/server.log"/>
<param name="Append" value="true"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %p - %m%n"/>
</layout>
</appender>
<root>
<priority value ="trace"/>
<appender-ref ref="appender"/>
</root>
</log4j:configuration>
Then you can see logging on console....

What is the best way to use log4j in the web application?

We are starting a Spring MVC based web application. We will be using tomcat as the web server.
I need to configure log4j in the application and log to the application specific file and not to the tomcat log files.
e.g. tomcat has its own log files like localhost.log etc. I want something like myAppName.log in the tomcats log folder.
The logging configuration will go in lo4j.xml or log4j.properties in the application war file.
Plus I dont want to hard code the output log file in the web application.
But I am not sure how to do this.
Please help me. As well correct me if I am wrong somewhere.
Do like this, initialize the logger with following code,
Logger log = Logger.getLogger(this.getClass());
log the information like follows,
log.debug("My message");
and place the log4j.xml in your class path. content like follows,
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="infoLogsFile" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="MyApplication.log"/>
<param name="Threshold" value="DEBUG"/>
<param name="MaxFileSize" value="100MB"/>
<param name="ImmediateFlush" value="TRUE"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
</layout>
</appender>
<root>
<priority value ="DEBUG" />
<appender-ref ref="infoLogsFile"/>
</root>
</log4j:configuration>
Do not forget to add the required jars like log4jXXX.jars and apache common logging jars. with this you will be able to see all log messages in MyApplication.log file creates in bin folder of your tomcat.
Try this:
Put the log4j jar as part of the web application
Do not put a configuration as part of your web application
Create your log4j.xml wherever you like
When you start tomcat provide this argument
-Dlog4j.configuration=file:///.../log4j.xml

Categories

Resources