I want to export the log of my app in a html file,until now the log is displayed on the console of eclipse.
in all my classes logs are defined by
private static Logger logger = Logger.getLogger (classname.class.getName ());
does anyone know how I can do this in java?
Re-configure a particular logger:
private static final Logger LOGGER
= Logger.getLogger(ClassName.class.getName());
static
{
try
{
LOGGER.addHandler(new FileHandler("mylog.xml"));
// if you don’t want additional console output:
LOGGER.setUseParentHandlers(false);
} catch(IOException ex)
{
throw new ExceptionInInitializerError(ex);
}
}
Or change the global configuration:
Create a properties file like this:
handlers=java.util.logging.FileHandler
java.util.logging.FileHandler.pattern=mylog2.xml
# add more options if you like
Run your application with -Djava.util.logging.config.file=<path to the file above>.
In either case:
Study http://docs.oracle.com/javase/7/docs/api/java/util/logging/LogManager.html and http://docs.oracle.com/javase/7/docs/technotes/guides/logging/overview.html
You may do that using Log4j or some library.
You can export as XML for example with http://logging.apache.org/chainsaw/
There must be something similar with HTML, have a look at http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/HTMLLayout.html
Related
I'm having a problem to print the log files after updating the log4 jars. Here is my implementation below. for the old version of log4j we only use the "PropertyConfigurator" for our logf4.properties (this is an external file). Im not sure if I missed something to declare but upon testing logs still not printing. The log4j version that im currently using now is the 2.17.2
private LoggerConfig (){
try {
//PropertyConfigurator.configureAndWatch(Constants.LOG_CONFIG);
LoggerContext context = (LoggerContext) LogManager.getContext(false);
File file = new File(Constants.LOG_CONFIG);
ConfigurationSource source = new ConfigurationSource(new FileInputStream(Constants.LOG_CONFIG), new File(Constants.LOG_CONFIG));
Configurator.initialize(null, source);
LOGGER = LogManager.getLogger(this.getClass());
LoggerContext.getContext().setConfigLocation(file.toURI());
LOGGER.debug("Log4j Properties successfully loaded.");
} catch (Exception e) {
LOGGER.error("Unable to load application properties file: " + Constants.LOG_CONFIG);
}
LOGGER.debug("Connection pool successfully initialized.");
}
you are using mostly LOGGER.debug, the logging level is set to DEBUG or lower?
if is set to a higher level please consider setting it to a level lower to debug or trace to validate the logf4.properties is proper linked
It is possible so simple, but I've wasted already a lot of time to find any solution.
I have
package net.rubyeye.xmemcached;
...
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
public class XMemcachedClient implements XMemcachedClientMBean, MemcachedClient {
private static final Logger log = LoggerFactory
.getLogger(XMemcachedClient.class);
....
With Log4j I get all logs from apache-servicemix.
I've tried something like
log4j.logger.net.rubyeye.xmemcached.XMemcachedClient=All, xmemcachedLog
log4j.appender.xmemcachedLog=org.apache.log4j.RollingFileAppender
log4j.appender.xmemcachedLog.File=${karaf.data}/log/spring/xmemcachedLog.log
log4j.appender.xmemcachedLog.ImmediateFlush=true
log4j.appender.xmemcachedLog.maxFileSize = 10MB
log4j.appender.xmemcachedLog.maxBackupIndex = 10
log4j.appender.xmemcachedLog.layout=org.apache.log4j.PatternLayout
log4j.appender.xmemcachedLog.layout.ConversionPattern=%d{dd-MM-yyyy_HH:mm:ss} %-5p [%t] - %m%n
But I don't get anything. I want to get information about exception which I get on the 1335th line
key = this.preProcessKey(key);
Actually, it doesn't matter that I want to log exactly that class. In my application I also have other classes which have LoggerFactory.getLogger(...);
And the main question is
How to get logs from Logger log = LoggerFactory
.getLogger(SomeClass.class);
Now, my rootLogger looks like
# Root logger
log4j.rootLogger=info, out, sift, osgi:VmLogAppender
log4j.throwableRenderer=org.apache.log4j.OsgiThrowableRenderer
You should have a logback.xml somewhere which decide to show your log or not if you're on a java EE application.
Try to add this line of code into it:
<logger name="net.rubyeye.xmemcached" level="DEBUG"/>
It will activate DEBUG logs for all the classes in this package.
If it still doesn't work maybe you don't have the file in your classpath and you might have to add it in the jvm parameter.
There is no problem in my logger. I've just hadn't any log.error() or log.smth() so I haven't got any lines in my files.
So it would work, for example, in that method inside XMemcachedClient
public void setTimeoutExceptionThreshold(int timeoutExceptionThreshold) {
if (timeoutExceptionThreshold <= 0) {
throw new IllegalArgumentException(
"Illegal timeoutExceptionThreshold value "
+ timeoutExceptionThreshold);
}
if (timeoutExceptionThreshold < 100) {
log.warn("Too small timeoutExceptionThreshold value may cause connections disconnect/reconnect frequently.");
}
this.timeoutExceptionThreshold = timeoutExceptionThreshold;
}
It shows me "Too small timeoutExceptionThreshold value may cause connections disconnect/reconnect frequently." in my ${karaf.data}/log/spring/xmemcachedLog.log when timeoutExceptionThreshold < 100
I want to use log4j for generating the logs.
For this I am using the following code :
package com.idm.Test;
import org.apache.log4j.Logger;
public class log4jExample {
static Logger log = Logger.getLogger(log4jExample.class.getName());
public static void main(String[] args) {
log.info("Hello this is a debug message 1");
log.info("Hello this is a debug message 2");
log.info("Hello this is a debug message 3");
}
}
My log4j properties file is given below :
# Define the root logger with appender file
log=G:\\logs
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}\\log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
I want to generate log file inside
G:\logs\log.out
But the problem is that when I run this. There is no log file is created on this path.
When I already created one file into that location with log.out name and run again it is not showing me the logs inside this file.
I put my log4j.properties file inside com.idm.Test package.
You are using the the Java Util Logger in your code
import java.util.logging.Logger;
this is not the log4j logger. Fix your import and ensure that your configuration file will be found (either put in on the classpath or specifiy the location with the log4j.configuration system property - see here)
Note: OP edited question and uses the right import now...
By the way do not use log4j (1) anymore. It has reached its EOL and is not Java 9 ready.
Go with log4j2 (or other current logging frameworks) instead.
I did same like your code and properity, and log file was created.
In my case, log4j.properties is located in the root of class path.
i.e.)
classes/log4j.properties
classes/com/idm/Test/log4jExample
please, check the location of log4j.properties.
You should put log4j.properties in resource folder (source/main/resource), i think it will work correctly.
In case your project is java project (not maven project) i think you should change your code:
package com.idm.Test;
import org.apache.log4j.Logger;
public class log4jExample {
static Logger log = Logger.getLogger(log4jExample.class.getName());
public static void main(String[] args) {
**PropertyConfigurator.configure("yourPath/log4j.properties");**
log.info("Hello this is a debug message 1");
log.info("Hello this is a debug message 2");
log.info("Hello this is a debug message 3");
}
}
I am trying to create multiple logs in Log4j, but I am facing a weird problem. Here's the log4j.properties and the code implementing it.
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILEALL
# Define the file appender
log4j.appender.FILEALL=org.apache.log4j.FileAppender
log4j.appender.FILEALL.File=${logfile.name}
# Define the layout for file appender
log4j.appender.FILEALL.layout=org.apache.log4j.HTMLLayout
#log4j.appender.FILEMAIN=org.apache.log4j.FileAppender
#log4j.appender.FILEMAIN.File=${logfilemain.name}
#log4j.appender.FILEMAIN.layout=org.apache.log4j.HTMLLayout
I have added the statement when running both and removed the original one
log4j.rootLogger = DEBUG, FILEALL , FILEMAIN
And this is the java code:
System.setProperty("logfile.name", savePath1);
// System.setProperty("logfilemain.name", savePath1);
logger = Logger.getLogger(HarishLog.class.getName());
PropertyConfigurator.configure("log4j.properties");
The code works perfectly fine till I make one log, but as soon as I enable the setting for 2nd log in either the properties or the javafile, nothing happens.
Besides I am unable to put a different name at
log4j.appender.FILEALL.File=${logfile.name}
it only works for logfile.name and logfilea.name, It doesn't work for any other name if I change it both in the javacode and the properties folder. Why is this???
Thank you
This works for me:
log4j.rootLogger = DEBUG, FILEALL, FILEMAIN
log4j.appender.FILEALL=org.apache.log4j.FileAppender
log4j.appender.FILEALL.File=${logfile.name}
log4j.appender.FILEALL.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILEMAIN=org.apache.log4j.FileAppender
log4j.appender.FILEMAIN.File=${logfilemain.name}
log4j.appender.FILEMAIN.layout=org.apache.log4j.HTMLLayout
import org.apache.log4j.Logger;
public class LogTest {
public static void main(final String... args) {
System.setProperty("logfile.name", "logall.txt");
System.setProperty("logfilemain.name", "logmain.txt");
Logger logger = Logger.getLogger(LogTest.class.getName());
logger.info("hello");
}
}
If you're still having problems, try adding:
log4j.debug = true
to the beginning of your log4j.properties, and check the output messages.
In weblogic I can configure in the console for the Serverlog to use log4j instead of default JDK logging.
However the serverlog is not using a log4j.properties file, but seems to use the configuration in config.xml
Even if the log4j.properties file is in the classpath and I set these properties:
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dlog4j.configuration=file:<path>/log4j.properties
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.log.Log4jLoggingEnabled=true
Is it possible to use log4j.properties configuration for Weblogic Server Logging, or can I only change the log4j configuration with java code?
I don't know anything about WebLogic in particular, but adding -Dlog4j.debug will cause log4j to tell you where it's looking for its configuration. I've found that to be invaluable when tracking down logging issues in tomcat previously.
Check out the docs for PropertyConfigurator and DOMConfigurator for details on the log4j configuration process.
If you put the log4j.xml in your classpath, WebLogic will pick it up. I use Apache Commons logging with log4j in WebLogic, and it's an easy thing to do. No need for those Java options.
Where are you setting the above options? Try putting the -Dlog4j option in the Server Start options for each managed server that will use log4j
To specify logging to a Log4j Logger instead of the default Java Logging:
* When you start the Administration Server, include the following Java option in the weblogic.Server command:
-Dweblogic.log.Log4jLoggingEnabled=true
From: http://edocs.bea.com/wls/docs103/logging/config_logs.html#wp1014610
I never got this working as I intented.
What I eventually did was create some kind of work-around.
I register a Handler that listens to the Weblogic serverlog.
From this handler I do my own logging to log4j. That logging can be redirected to do anything I want.
create a custom logHandler:
public class CustomLogHandler extends Handler {
..
public CustomLogHandler () throws SecurityException, IOException,
NamingException {
String log4jConfig = LogFilterConfiguration.getLog4jDirectory();
classlogger.info("log4j configured for file"+ log4jConfig );
PropertyConfigurator.configure(log4jConfig);
logFilterConfiguration = new LogFilterConfiguration();
}
public void publish(LogRecord record) {
WLLogRecord rec = (WLLogRecord) record;
if (!isLoggable(rec))
return;
if (getLoggerName().. is something i want to log) {
// do my own log4j logging
}
then create an ApplicationLifecycleListener.
with a postStart method:
public void postStart(ApplicationLifecycleEvent evt) {
Logger logger = LoggingHelper.getServerLogger();
Handler oldHandler = null;
Handler[] currentHandlers = logger.getHandlers();
.. code to remove an old custom handler if exists...
with something like logger.removeHandler(oldHandler);
// add custom handler to serverlogger.
CustomLogHandler h = null;
try {
h = new CustomLogHandler ();
// If handler was removed we can add a new version.
if (!(unRemovedHandlerClasses.contains(h.getClass()))){
logger.addHandler(h);
registerMBean(h) ;
}
} catch (Exception nmex) {
classLogger.error("Error adding CustomLogHandler to serverlogger "
+ nmex.getMessage());
logger.removeHandler(h);
}
}