When I log a message in the code the server prints twice the same message with the only difference of the date at the beginning.
I'm using the default log configuration that comes with the server Wildfly 10.
Server.log
09:43:09,122 INFO [es.myapp.business.scheduler.boundary.Job] (default task-91) ----------INIT Job Mon Nov 20 10:05:08 CET 2017
2017-11-20 09:43:09,122 INFO [es.myapp.business.scheduler.boundary.Job] (default task-91) ----------INIT Job Mon Nov 20 10:05:08 CET 2017
Job.java
import org.apache.log4j.Logger;
...
public class Job {
protected Logger logger = Logger.getLogger(getClass().getName());
public void execute() throws IOException {
logger.info("----------INIT Job " + new Date());
}
}
Wildfly logging.properties
# Note this file has been generated and will be overwritten if a
# logging subsystem has been defined in the XML configuration.
# Additional loggers to configure (the root logger is always configured)
loggers=sun.rmi,org.jboss.as.config,com.arjuna
logger.level=INFO
logger.handlers=FILE,CONSOLE
logger.sun.rmi.level=WARN
logger.sun.rmi.useParentHandlers=true
logger.org.jboss.as.config.level=DEBUG
logger.org.jboss.as.config.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=enabled,autoFlush,target
handler.CONSOLE.enabled=true
handler.CONSOLE.autoFlush=true
handler.CONSOLE.target=SYSTEM_OUT
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.append=true
handler.FILE.autoFlush=true
handler.FILE.enabled=true
handler.FILE.suffix=.yyyy-MM-dd
handler.FILE.fileName=/home/u24282/servers/wildfly-10.1.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
Are you perhaps piping your WildFly process output to the log file? Or, are you running in domain mode maybe?
Related
I use logger(Log4j) to create my file log program.
log4j.properties file:
# Root logger option
log4j.rootLogger=DEBUG, stdout, file
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\WorkSpace\\ToDoList\\src\\log\\log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
My class:
import org.apache.log4j.Logger;
#WebServlet("/Login")
public class LoginApp extends HttpServlet {
private static final long serialVersionUID = 1L;
private final static Logger logger = Logger.getLogger(LoginApp.class);
private final static HibernateToDoListDao actions = HibernateToDoListDao.getInstance();
public LoginApp()
{
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
{
try
{
logger.info("The user: "+ username+" connect to app.");
request.getRequestDispatcher("Index.jsp").forward(request, response);
}
catch(ToDoListDaoException e)
{
System.out.println(e.getMessage());
}
}
}
My file log:
2017-01-14 17:14:29 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
2017-01-14 17:14:29 DEBUG TwoPhaseLoad:131 - resolving associations for [model.User#1]
2017-01-14 17:14:29 DEBUG TwoPhaseLoad:239 - done materializing entity [model.User#1]
2017-01-14 17:14:29 DEBUG StatefulPersistenceContext:892 - initializing non-lazy collections
2017-01-14 17:14:29 DEBUG ConnectionManager:427 - aggressively releasing JDBC connection
How can i write only my messages logs to file without other details.
e.g. in my class only the line
"logger.info("The user: "+ username +"connect to app.")"
will write to the file.
Thanks
You need to set the package name in log4j configuration file for which you want to enable logging. Your configuration file should look like below. Remember to write your package name in 2 line -
# Root logger option
log4j.rootLogger=ERROR, stdout, file
# Write your package Name here
log4j.logger.packageName=DEBUG, stdout, file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\WorkSpace\\ToDoList\\src\\log\\log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Summary
We're struggling with enabling log4j's TRACE level in a custom Documentum DFS application. The application runs on Tomcat 7.0 and uses Log4j 1.2.13, and is packaged as a WAR archive.
We have an appender called CustomServiceAppender that works just fine with all the other levels, i.e. DEBUG and upwards. During development we have this appender configured for the DEBUG level, and for production we change it to INFO or WARN. The logging then behaves like we expect (it limits the logging).
However we have written some code that logs at the TRACE level that we want to see in our logs. We've tried restarting, redeploying, deleting cache, checking log4j and commons-logging versions (they are 1.2.13 and 1.1.1, respectively). Also, there is no XML configuration file, and we know that our properties file is being picked up.
We use the default logger from DFS, namely the DfLogger class.
Changing the configuration - why doesn't it work?
In log4j.properties we change the following line from
log4j.logger.com.mycompany.services=DEBUG,CustomerServiceAppender
to
log4j.logger.com.mycompany.services=TRACE,CustomerServiceAppender
... which does not work! However, the following does work:
log4j.logger.com.mycompany.services=INFO,CustomerServiceAppender
What's happening here? Why can't we enable TRACE?
log4j.properties
For reference, here's our complete configuration file (identifying names altered):
#------------------- COMMON LOGGING LEVELS --------------------------
log4j.logger.com.emc.documentum.fs.rt = WARN, A1, F1
log4j.logger.com.emc.documentum.fs.datamodel = WARN, A1, F1
log4j.logger.com.emc.documentum.fs.services = WARN, A1, F1
log4j.logger.com.emc.documentum.fs.tools = WARN, A1, F1
log4j.logger.com.documentum.debug=ERROR, A1, F1
log4j.rootLogger=ERROR, A1
#------------------- CONSOLE LOG --------------------------
log4j.logger.com.mycompany.services=ERROR,A1
log4j.appender.A1.Threshold=ERROR
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{ISO8601} %5p [MYCOMPANY-SP] %c - %m%n
#------------------- ALL --------------------------
log4j.appender.F1=org.apache.log4j.RollingFileAppender
log4j.appender.F1.File=E\:/Documentum/logs/dfs-runtime.log
log4j.appender.F1.MaxFileSize=10MB
log4j.appender.F1.layout=org.apache.log4j.PatternLayout
log4j.appender.F1.layout.ConversionPattern=%d{ISO8601} %5p [MYCOMPANY-SP] %c- %m%n
#------------------- ASPECT_TRACE --------------------------
log4j.logger.com.emc.documentum.fs.tracing = DEBUG, ASPECT_TRACE
log4j.appender.ASPECT_TRACE=org.apache.log4j.RollingFileAppender
log4j.appender.ASPECT_TRACE.File=E\:/Documentum/logs/dfs-runtime-trace.log
log4j.appender.ASPECT_TRACE.MaxFileSize=10MB
log4j.appender.ASPECT_TRACE.layout=org.apache.log4j.PatternLayout
log4j.appender.ASPECT_TRACE.layout.ConversionPattern=%d{ISO8601} %5p [MYCOMPANY-SP] %m%n
#------------------- Customer TBO --------------------------
log4j.logger.no.customer=DEBUG,CustomerTBOAppender
log4j.appender.CustomerTBOAppender=org.apache.log4j.RollingFileAppender
log4j.appender.CustomerTBOAppender.File=E\:/Documentum/logs/CustomerTBO.log
log4j.appender.CustomerTBOAppender.MaxFileSize=10MB
log4j.appender.CustomerTBOAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.CustomerTBOAppender.layout.ConversionPattern=%d{ISO8601} %5p [MYCOMPANY-SP] [%t] %c - %m%n
#------------------- Customer Service --------------------------
log4j.logger.com.mycompany.services=TRACE,CustomerServiceAppender
log4j.appender.CustomerServiceAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.CustomerServiceAppender.File=E\:/Documentum/logs/CustomerService.log
log4j.appender.CustomerServiceAppender.Append=true
log4j.appender.CustomerServiceAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.CustomerServiceAppender.layout.ConversionPattern=%d{ISO8601} %5p [MYCOMPANY-SP] [%t] %c - %m%n
****************************************************************************************
I am using a third party library (Sphinx) which uses java.util.logging. I have been trying several approaches to route its logs to slf4j. The logging library I wish to use is Log4j2, which is configured like this:
Configuration:
properties:
property:
- name: logPath
value: logs
- name: logName
value: flux
- name: rootLevel
value: info
- name: useConsole
value: ALLOW
Appenders:
Console:
name: Console
target: SYSTEM_OUT
ThresholdFilter:
level: ${sys:rootLevel}
onMatch: ${sys:useConsole}
PatternLayout:
pattern: "%d{yyyy.MM.dd G HH:mm:ss,SSS z} %-5p [%t] %C{2} (%F:%L) - %m%n"
RollingRandomAccessFile:
name: File
fileName: "${sys:logPath}/${sys:logName}.log"
filePattern: "${sys:logPath}/${sys:logName}.%d{yyyy-MM-dd}.log"
PatternLayout:
pattern: "%d{yyyy.MM.dd G HH:mm:ss,SSS z} %-5p [%t] %C{2} (%F:%L) - %m%n"
Policies:
TimeBasedTriggeringPolicy:
interval: 1
Loggers:
Root:
level: ${sys:rootLevel}
AppenderRef:
- ref: File
- ref: Console
I applied without success all the solutions I could find on this and other forums. Among others:
I added this maven dependency to my POM:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.7.20</version>
</dependency>
I also tried with calling this in a static block:
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
And tried setting the system property:
System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");
In my last attempt I passed the VM argument:
-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
and got the exception below:
Could not load Logmanager "org.apache.logging.log4j.jul.LogManager"
java.lang.ClassNotFoundException: org.apache.logging.log4j.jul.LogManager
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.util.logging.LogManager$1.run(LogManager.java:195)
at java.util.logging.LogManager$1.run(LogManager.java:181)
at java.security.AccessController.doPrivileged(Native Method)
at java.util.logging.LogManager.<clinit>(LogManager.java:181)
at org.chatbot.stt.SttEngineDemo.<clinit>(SttEngineDemo.java:25)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
Am I doing something wrong? What else can I try?
Update:
I also tried redirecting jul to log4j2, bypassing slf4j, hence changing my original strategy (thanks for the suggestion #rgoers).
In order to do this, I added the dependency below:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jul</artifactId>
<version>2.5</version>
</dependency>
and also set the System property
java.util.logging.manager to: org.apache.logging.log4j.jul.LogManager
Then the sphinx logs are gone. I know they are not routed to my log4j2 logger since most of the Sphinx logs have the level INFO and they should be processed by log4j2. So still not correct.
If you want to route the messages to Log4j 2 why not just use Log4j 2's bridge? log4j-jul-2.5.jar
We have a solution here working and the difference I noticed is: logger.setUseParentHandler(false) and logger.addHandler(new org.slf4j.bridge.SLF4JBridgeHandler());
I make sure I don't have any other handler and then attach the SLF4JBridgeHandler to the Logger instance.
import java.io.File;
import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;
class Helper {
public static Logger get(String name) {
Logger logger = Logger.getLogger(name);
logger.setUseParentHandlers(false);
configureLogger(logger);
return logger;
}
private static void configureLogger(Logger logger) {
try {
// Remove Console Handler
Handler[] handlers = logger.getHandlers();
for (int i = handlers.length - 1; i >= 0; --i) {
logger.removeHandler(handlers[i]);
}
// Add handler for SLF4J
logger.addHandler(new org.slf4j.bridge.SLF4JBridgeHandler());
} catch (Throwable ex) {
logger.log(Level.SEVERE, "configureLogger", ex);
}
}
}
I have a JEE-Webapp, an wanted to log servlet-filter.
The underlying Tomcat 8.5 has already initialized the JUL at startup.
So I needed to override the Tomcat-initialization.
This code worked for me.
SLF4JBridgeHandler.removeHandlersForRootLogger();
LogManager manager = LogManager.getLogManager();
Enumeration<String> loggernames = LogManager.getLogManager().getLoggerNames();
while(loggernames.hasMoreElements()) {
String loggername = loggernames.nextElement();
Logger logger = manager.getLogger(loggername);
Handler[] handlers = logger.getHandlers();
for (int i = handlers.length - 1; i >= 0; --i) {
logger.removeHandler(handlers[i]);
logger.setUseParentHandlers(true);
}
}
SLF4JBridgeHandler.install();
// Decision what to log is on slf4j-Side. So we delegate every log-request.
Logger.getLogger("").setLevel(Level.FINEST);
I've got a simple Tomcat web service that I'd like to see the logs for. I figured log4j would be the easiest solution. So far it will log to the in my dev environment, but it won't log to a file.
Here is my log4j.properties file (located in the src/ folder):
#Add these properties to all CallRouter-->data-->ddlog4j.properties files at the bottom to configure the Transactions.jar logging for DB and WS messaging.
log4j.rootCategory=ALL, MAIN_LOG
log4j.rootLogger=DEBUG,console
#Defines the <logging level>, <appender> for custom logging.
log4j.category.com.ddvc.android.resource=INFO, SupportWebServices
#### Transactions.jar appender INFO setup
log4j.logger.com.ddvc.android.resource=INFO
log4j.appender.ResourceInfo=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ResourceInfo.File=C:/test/SupportWebServices.log
log4j.appender.ResourceInfo.Append=true
log4j.appender.ResourceInfo.DatePattern='.' yyyy-MM-dd HH-mm
log4j.appender.ResourceInfo.layout=org.apache.log4j.PatternLayout
log4j.appender.ResourceInfo.layout.ConversionPattern=%d{[yyyy-MM-dd HH:mm:ss:SSS]} %p %c{1} (%M: %L) - %m%n
log4j.appender.ResourceInfo.Threshold=INFO
# Output to Console
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{[yyyy-MM-dd HH:mm:ss]} %p %c{1} (%M: %L) - %m%n
log4j.appender.CONSOLE.Threshold=CONSOLE
And in my java files I have (located in src/com/ddvc/android/resource):
import org.apache.log4j.Logger;
#Path("/pulse")
#Component
#Scope("request")
public class PulseResource {
private final static Logger LOGGER = Logger.getLogger(PulseResource.class.getName());
#GET
#Path("list")
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public List<Pulse> postXML() {
LOGGER.info("Start: list");
}
}
Like I said I can see the logs to the Console:
INFO [2015-02-19 15:19:34,961] [http-bio-8080-exec-3] [PulseResource] [] - Start: list
But I don't see any file created or logged to in the C:\test folder. (plan to change it to ${catalina.base}\logs\SupportWebServices.log)
Try changing
log4j.rootLogger=DEBUG,console
to
log4j.rootLogger=DEBUG,console,ResourceInfo
remove this line:
log4j.rootCategory=ALL, MAIN_LOG
edit this line:
log4j.rootLogger=DEBUG,console,ResourceInfo
How to know in log4j , that ERROR level is triggered. In my code I have written like If an exception occurs i.e if an ERROR level is triggered then I will show log file path in console and wont show any message for other levels.
In Log4j you can configure different levels in the log4j.properties or xml file which ever you choose to use.
There is some predefined pattern with the error levels and runs from lower to upper.
Lowest id Debug its in this sequence.
1.Debug
2. Warn
3. Error etc
So if you want only Error messages then configure the Error level to Error. you wot get Debug and Warn
If you configure Debug you get everything
Ex.
<logger name="org.springframework...">
<level value="error" />
</logger>
This is the point of separating the code from the configuration.
E.g., your code could look like this:
try {
someMethod();
} catch (SomeException e) {
log.error("Error!!! " + e.getMessage());
}
And in your log4j configuration, your configure your log to output only ERROR level messages:
log4j.rootLogger=error, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# Just an example of a pattern layout
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n