How to setup LogBack Configuration - java

I'm completely new to LogBack, and I'd like to use it. I notice that you can use a Configuration as an XML, but I have no idea how to implement that XML and have Logback use that instead of the default one.
My programs packages are like me.iarekylew00t.a.b and so on. It'll also be compiled into a runnable JAR at the end. How should I go about adding a logback.xml file, without the enduser needing to have it?
Sorry if this is a noob question, but I've been trying to look this up for hours and I can't find anything that clearly tells someone how to go about adding a configuration - most assume you already know how... Thanks. (please be as detailed as possible)

Add a logback.xml in the root of your classpath containing (tune to your needs):
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</encoder>
</appender>
<logger name="some.logger.name" level="INFO"/>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>
and that's all.
EDIT: usual directory structure:
src/main/java/
some/package/
someClass.java
some/other/package/
someOtherClass.java
src/main/resources/
logback.xml
in the jar:
some/package/
someClass.class
some/other/package/
someOtherClass.class
logback.xml

I had the same issue and resolved it by copying logback.xml to src/main/java - this was the only way I found to make the executable JAR find it and use it.
Since I didn't want to have two (possibly different) config files, I kept the original logback.xml in my src/resources folder (where Eclipse would find it and use it during development) and replaced the one under src/main/java with a symlink. Works well for me.

Related

Logback does not write logs to a file

I have a Java-standalone REST application, which is inside Tomсat. I need to output logs to a file, I use logback. But logs are not written to the file. They are displayed in the console, although I removed the console appender. If you try on a Windows machine, everything goes fine. Trying on RedHat (does not have a GUI), the logs are not output to the file (although they should) and are output to the console (although they should not be displayed). The application works exactly, responds to queries.
Logback.xml:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="DEV_HOME" value="/var/tmp" />
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${DEV_HOME}/mytest.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${DEV_HOME}/mytest-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>2KB</maxFileSize>
<maxHistory>4</maxHistory>
<totalSizeCap>10KB</totalSizeCap>
</rollingPolicy>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="file" />
</root>
</configuration>
In Eclipse I do export to Runnable jar file, I throw it on a Linux machine. I run as follows:
java -jar test.jar &
Yes I had the same scenario with jboss EAP 7.0 every thing was working fine on the window machine but as soon as i was taking it to linux machine . it wont write a single word.
[application.properties for logging]
second i had move log4j.properties in Jboss bin folder. application.properties file and the same file in springboot application resources.
After that restart the server and you will found the loggs written on the specified folder

How to extract output of retire.js into a file from maven execution

I am using retire.js plugin in maven pom file. The vulnerability details are listed along with the build output.
I would like to extract the retire.js output into a separate file.
Can you please suggest some ways to extract only retire.js data into a file.
Looking into the source code of retire.js Maven plugin we can notice that the log output from retirejs is redirected into Maven's stream (in initMiniLog()). And there seem to be no specific configuration for it.
However, with a bit of tweaking we can set up Maven to gather these logs. So I can suggest the following:
1) By default Maven uses slf4j-simple logger, remove its jar from {M2_HOME}/lib.
2) Place in the same folder a logging library that supports output into files, for example Logback: logback-classic-*.jar and logback-core-*.jar.
3) Define a configuration that will output everything into stdout and only the things that you are looking for into the file. logback.xml should be placed into {M2_HOME}/conf/logging. For example, I used the following draft configuration to extract the output of maven-compiler-plugin into maven.log in the current folder:
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>./maven.log</file>
<encoder>
<pattern>%message%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%level - %message%n</pattern>
</encoder>
</appender>
<!--
specify the package of retirejs: com.h3xstream.retirejs
-->
<logger name="org.apache.maven.plugin.compiler" level="TRACE">
<appender-ref ref="FILE" />
</logger>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
4) Execute your build command...

Share Spring Boot YAML configuration between two applications

I have two applications in the same maven project and have given each of them their own configuration file by setting the spring.config.name property for each before invoking SpringApplication.run().
Thus, in the first application, I set spring.config.name to server1 so it looks for server1 instead of application.yml. In the second I have set spring.config.name to server2.
However I would like them to share the same logging configuration. Unfortunately, logging configuration cannot be imported via #PropertySource since logging is already configured before property-sources are read - see Logging section of Spring Boot manual.
Is there any way I can do this?
Spring Boot uses as default Logback. You can put a logback.xml file in src/main/resources to configure the log. And both applications will automatically use this file to configure their logging engine.
You can learn how to configure Logback here: http://logback.qos.ch/manual/configuration.html
A simple example. It will set the log level to INFO and log to the Console:
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
</configuration>

Logback-classic in Jboss and Spring

I'm working on a project where I thought I would try using logback-classic for debugging and log rotation. I'm using this in a Maven context for building and creating a .war file to be deployed in JBoss 7.1 Application Server.
I've placed a logback.xml file in the resources folder in the code and a logback-test.xml in test/resources.
The active jar I'm using is the SLF4J to print the actual debugging.
public class MyClass extends MultiActionController {
private Logger logger = LoggerFactory.getLogger(MyClass.class);
public MyClass() {
logger.debug("hello");
}
}
When I run a JUnit test on the code in Maven itself it works, but after building a .war file i don't get any debugging in STDOUT nor can I find a file created.
I know that I've removed the actual logging from STDOUT in the config file, but where is the logging going...
the logback.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>logs/myproject.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyMMdd HH:mm:ss.SSS} [%-5.5level] [%-25.25logger] %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration>
The folder "logs" do I need to explicit create it in the JBoss instance or need to refer relative to it for this to work? Or is there something I missed? Do I need to put the logback.xml file in the JBoss instance?
best,
Henrik
Firstly you should ensure that the logback.xml is at the classpath, e.g. WEB-INF/classes/logback.xml as the mentioning at Chapter 3: Logback configuration.
The Chapter 4: Appenders mentions about FileAppender and RollingFileAppender properties as
file *String* The name of the file to write to. If the file does not exist, it is created. On the MS Windows platform users frequently forget to escape back slashes. For example, the value c:\temp\test.log is not likely to be interpreted properly as '\t' is an escape sequence interpreted as a single tab character (\u0009). Correct values can be specified as c:/temp/test.log or alternatively as c:\temp\test.log. The File option has no default value.
If the parent directory of the file does not exist, FileAppender will automatically create it, including any necessary but nonexistent parent directories.
The example is for logback.xml is as the following:-
<configuration>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logFile.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- daily rollover -->
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- keep 30 days' worth of history -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration>
I hope this may help.
You need to define the file-tag (as the previous answers already said). But you also need to know how it's interpreted. Logback sees it as relative to the application it's used in. So if you only use
<file>logs/<myfile>.log</file>
logback should create a "logs"-folder in the root of your JBoss (more specific: the folder where the .sh-script you start it with is located). Check from the root of your JBoss to see if you can find your logs-folder and file from there.

log4j 2 - configuration issue

I am trying to configure log4j 2.0 to report logs.
My config is saved as log4j2.xml and this is its content:
<?xml version="1.0" encoding="UTF-8"?>
<configuration name="PRODUCTION" status="OFF">
<appenders>
<RollingFile name="MyFileAppender"
fileName="../Logs/app.log"
filePattern="../Logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy />
<TimeBasedTriggeringPolicy interval="6" modulate="true"/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>
</appenders>
<loggers>
<root level="trace">
<appender-ref ref="MyFileAppender"/>
</root>
</loggers>
</configuration>
It exists in the classpath of the project and I tried putting it in many other directories..
I created a logger in the code like so:
Logger logger = LogManager.getLogger(MyClass.class.getName());
logger.info("test");
And nothing is written and no file is created.
When I debug the code I see that the logger is the default logger(console).
place log4j2.xml file under src/main/resources. It works
Actually This is a straight forward process. Two main classes of Log4j 2 are as follows that you need to import like this:
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
Now get a Logger instance by using this code.
private static final Logger logger = LogManager.getLogger();
Note I didn't specified the class name to getLogger() method as a parameter. Log4j 2 automatically figures it out.
Now you can use any of the info(), trace(), debug(), warn(), error(), fatal() method from the Logger class. But to get the output from all of these methods you'll need a XML configuration file. By default Log4j 2 only produces output from the error() and fatal() methods.
Configuration file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="MyCustomLogFile" fileName="/home/me/mylogfile.log">
<PatternLayout>
<Pattern>%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
</File>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="all">
<AppenderRef ref="MyCustomLogFile"/>
<!--<AppenderRef ref="Console"/>-->
</Root>
</Loggers>
</Configuration>
Save this file with any name any where. I use Log4j2.xml as name. Now you'll need this file to be put in classpath, which you can do by passing a system property when running the program as follows:
java -Dlog4j.configurationFile=/path/to/xml/configuration/file/Log4j2.xml MyMainClass
And you've done it. Logging will be right away on your console.
Special Notes:
In XML file I've provided 2 appenders: A file and a console. You can see that you just need to uncomment the commented AppenderRef tag to get output in a file instead of console.
You can also provide an environment variable as a system property. Log4j 2 will read the configuration file from the environment variable first and then in -D argument if not found an environment variable.
Have fun with logging. :-)
you should put your log4j2.xml into the classpath.
or set "log4j.configurationFile" system property to force to use your log4j2.xml
Please refer to: http://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration
It exists in the classpath of the project and I tried putting it in
many other directories.
Where exactly? There is often confusion about where "in the classpath" means. It can't just be anywhere. It has to be at the 'top' or the 'default package'.
src
├── main
│   └── java
│   ├── com
│   │   └── example
│   └── log4j2.xml
A tip for eclipse users:
Right click on the project and click "refresh". Make sure you could see the log4j2.xml file in eclipse.
(This solved my problem.)
To be verbose:
You shouldn't add the file to build path.(If you do, eclipse will warn you about this)
The name of this file doesn't appear in '.classpath' file.
I put my log4j2.xml under src/ directory. It works.
I had similar problem. I put the file under src folder and it worked. I did not mention any package name in the log4j2.xml file.
In the documentation of log4j 2: http://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration
"If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath."
but it is not working with classpath. Instead if we keep it in src folder, then it is working.
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>log4j2.xml</param-value>
</context-param>
similar problem is mentioned here : https://issues.apache.org/jira/browse/LOG4J2-357
I had the problem, I tried some solutions, but only this worked to me:
Go to web.xml, and add this parameter:
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>log4j2.xml</param-value>
</context-param>
I'm quite sure that you have to write down the full qualified name of the class whose messages you want to be logged - something like com.application.log4jtest.YourClass. If that doesn't work, try fiddling with the log level.
Also - just as a notice - you can also write
Logger logger = LogManager.getLogger(MyClass.class); // omit .getClass()
I also faced the same problem.I kept my log4j2.xml file in System environment variable.
Variable name : sys_logroot Variable value : D:\user\gouse
and no logs are created for me.
use the system variable-Dlog4j.configurationFile=path/to/log4j2.xmlSee here
This solve my problem
I had the same 'ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.' message over and over. It made me crazy. The log4j2.xml file was placed correctly at src/main/resources, like i did at thousands of projects before.
The solution in my case was to remove <packaging>pom</packaging> from the root pom.xml. packaging pom causes the content of src/main/resources not to be copied to target/classes.
Happy logging for anyone with the same root cause.
Ok, I solved the problem.
I had to specify in the xml the package="myPackage"

Categories

Resources