I have been using Tomcat,JBoss,Glassfish etc for years.
In these containers I have used Log4j, JDK Logging etc. It is very easy.
I am struggling to get any logging from my application in Weblogic 12c.
The logs get written to stderr and not to a log file.
private final static Logger log = Logger.getLogger(TestingService.class.getName());
log.log(Level.SEVERE,"My log " + text);
In the Admin console
Logging implementation: JDK
Severity level: INFO
The behaviour is the same if I configure Log4J by following the log4j Weblogic config process.
You can try some codes like the following to get the Weblogic domain logger and server logger in your application:
import java.util.logging.Logger;
import weblogic.logging.LoggerNotAvailableException;
import weblogic.logging.LoggingHelper;
public class GetLogger {
public static Logger getLogger(){
Logger logger = null ;
try {
logger = LoggingHelper.getDomainLogger() ;
} catch (LoggerNotAvailableException e) {
logger = LoggingHelper.getServerLogger() ;
}
return logger ;
}
}
Related
I'm actually adding java logging (can't use other framework) to my project. I build my app on a .war, and deployed it over Weblogic, the logger is working with my logging.properties config, except for the formatter i don't know why the app is ignoring it.
This is my class where i prepare the logger;
public class CtgLogger {
private static final String LOAD_ERROR = "Properties could not be loaded.";
private static final Map<String, Level> LEVEL_MAP;
private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
static {
final InputStream inputStream = CtgLogger.class.getResourceAsStream("/logging.properties");
try {
LogManager.getLogManager().readConfiguration(inputStream);
} catch (Exception e) {
Logger.getAnonymousLogger().severe(LOAD_ERROR);
Logger.getAnonymousLogger().severe(e.getMessage());
}
// and I add the LEVEL_MAP to the logger...
And this is my properties...
handlers = java.util.logging.FileHandler
java.util.logging.FileHandler.pattern=logsfolder/CTGLOG_%g.log
java.util.logging.FileHandler.level=ALL
java.util.logging.FileHandler.limit=3000
java.util.logging.FileHandler.count=6
#java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
#If I use the SimpleFormatter, apps goes well with it format.
java.util.logging.FileHandler.formatter = com.package.my.log.JsonCustomFormatter
#If I use my custom formatter, the weblogic works with a XMLFormatter (default)
I know the .properties is working, because logger is working with the pattern, limit and count I setted.
PD: If i run my app with JUnit, logs are working with my custom formatter, but do not at weblogic! Don't know why!
Weblogic is going to have multiple class loaders. The standard LogManager can only see classes loaded via the system class loader. Check the Server Log for errors related to not finding your custom class. If that is the case, you have to move your formatter to the system classloader. Otherwise you have have to use code to install your formatter from your web app which is running in a child classloader.
There are also bugs in the LogManager.readConfiguration and alternative methods to use in JDK9 and later.
Using Eclipse and java standard logger may be painful. I found something to produce similar output to Log4J:
"%d{HH:mm:ss,SSS} %-5p %m (%F:%L) in %t%n" in Log4J : you can click on reference and you are there log was issued
21:36:37,9 INFO process model event Digpro2021a/digpro.Digpro(Digpro.java:358) in processModelEvent
21:36:37,9 INFO start polling Digpro2021a/digpro.Digpro(Digpro.java:398) in processEventAutoreload
21:36:37,9 INFO reload now Digpro2021a/digpro.Digpro(Digpro.java:370) in processModelEvent
public class Digpro {
protected static final Logger L = Logger.getLogger("Digpro");
//logger conf
static {
L.setLevel(Level.FINE);
Handler handler = Logger.getLogger("").getHandlers()[0];
handler.setLevel(Level.FINE); // Default console handler
handler.setFormatter(new Formatter() {
#Override
public String format(LogRecord r) {
Date d = new Date(r.getMillis());
String srcClassLong = r.getSourceClassName();
String[] aClass = srcClassLong.split("\\$")[0].split("\\.");
String srcClass = aClass[aClass.length - 1];
StackTraceElement elem = (new Throwable()).getStackTrace()[7];
int line = elem.getLineNumber();
String modulName = elem.getModuleName();
return String.format("%tH:%tM:%tS,%tl %.7s %s %s/%s(%s.java:%d) in %s\n", d, d, d, d, //
r.getLevel(), r.getMessage(), // LEVEL and message
modulName, srcClassLong, srcClass, line, r.getSourceMethodName()); //ref to click on
}
});
}
...
public static class TestDigpro extends Digpro {
//TESTING:
#Test
public void testLogFormat() {
L.info("poll info");
L.fine("got fine");
}
}
}
produses:
21:51:20,9 INFO poll info Digpro2021a/digpro.Digpro$TestDigpro(Digpro.java:723) in testLogFormat
21:51:20,9 FINE got fine Digpro2021a/digpro.Digpro$TestDigpro(Digpro.java:724) in testLogFormat
I'm able to programmatically set the logging level on the application with the following code, but is it also possible to do this on a package level, say com.somepackage.* where I want the level to be only ERROR rather than DEBUG or INFO on said package?
// Sets the logging level to INFO
LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.INFO);
But I can't seem to find a way to set it on a package level...
You should set the package name as logger-name
// Sets the package level to INFO
LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
Logger rootLogger = loggerContext.getLogger("com.somepackage");
rootLogger.setLevel(Level.INFO);
You should be able to get the package name more elegant, but this is basically it.
This follows the tree like hierarchy for the Logger Context:
Logger Context
You can do it by using logback..
Logger LOG = (Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
LOG.setLevel(Level.WARN);
This solved my problem.
You can get the SLF4J logger for the package and cast it to Logback logger. Less code that #dimitri-dewaele's.
((Logger) LoggerFactory.getLogger("com.somepackage")).setLevel(DEBUG)
#nandu-prajapati's approach is similar, except that it sets the root logger level, not the one desired.
In case you don't want to change the logback-classic to a compile-time dependency, here is some code that uses reflection to set this level assuming that logback is used as the slf4j runtime-binding. Here AbcClass is the class whose logger level you want to change to TRACE:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SomeClass {
private static final Logger logger = LoggerFactory.getLogger(SomeClass .class);
public static void beforeEachTest() throws Exception {
final Logger loggerInterface = LoggerFactory.getLogger(AbcClass.class);
String loggerLevelNew = "TRACE";
if (!loggerInterface.isTraceEnabled()) {
try {
Class<?> levelLogBackClass = Class.forName("ch.qos.logback.classic.Level");
Method toLevelMethod = levelLogBackClass.getDeclaredMethod("toLevel", String.class);
Object traceLvel = toLevelMethod.invoke(null, loggerLevelNew);
Method loggerSetLevelMethod= loggerInterface.getClass().getDeclaredMethod("setLevel", levelLogBackClass);
loggerSetLevelMethod.invoke(loggerInterface, traceLvel);
} catch (Exception e) {
logger.warn("Problem setting logger level to:{}, msg: {}", loggerLevelNew, e.getMessage());
throw e;
}
}
}
}
Something similar can be done for log4j and JDK logging to make this (kind-of) library agnostic
I have 2 configuration files for logging,
config1.properties and
config2.properties
When I load the config1.properties and log something, the format is correct, but right after, when I load the second config file, the changes are not reflected. Here is my code:
System.setProperty("java.util.logging.config.file", "config1.properties");
logger = Logger.getLogger(this.getClass().getSimpleName());
logger.info("Message 1");
System.setProperty("java.util.logging.config.file", "config2.properties");
LogManager logManager = LogManager.getLogManager();
logManager.readConfiguration();
logger = Logger.getLogger("NewLogger");
logger.info("Message 2");
I have set the configuration in config2.properties to log messages in 2 lines, however the message is still showing in one line.
Any ideas why the new configuration is not taking effect? I am sure that my config files are correct, because I tried loading config2 before config1, and that showed my logged messages in 2 lines.
Here is the logged result:
[01-13-2014 16:48:56:186] LoggerUnitTest INFO: Message 1
[01-13-2014 16:48:56:195] LoggerUnitTest INFO: Message 2
It should show up as :
[01-13-2014 16:48:56:186] LoggerUnitTest INFO: Message 1
[01-13-2014 16:48:56:195] LoggerUnitTest INFO:
Message 2
Below are the config files I am using:
config1.properties
handlers=java.util.logging.ConsoleHandler
.level= FINE
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.formatter.format = [%1$tm-%1$td-%1$tY %1$tk:%1$tM:%1$tS:%1$tL] %4$s: %5$s%6$s%n
config2.properties
handlers=java.util.logging.ConsoleHandler
.level= FINE
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
# Note that this line is different from the line in config1
java.util.logging.ConsoleHandler.formatter.format = [%1$tm-%1$td-%1$tY %1$tk:%1$tM:%1$tS:%1$tL] %n %4$s: %5$s%6$s%n
This works for me:
Test.java
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class Test {
public static void main(String[] args) throws Exception {
System.setProperty("java.util.logging.config.file", "config1.properties");
Logger logger = Logger.getLogger(Test.class.getSimpleName());
logger.info("Message 1");
System.setProperty("java.util.logging.config.file", "config2.properties");
LogManager logManager = LogManager.getLogManager();
logManager.readConfiguration();
logger = Logger.getLogger(Test.class.getSimpleName());
logger.info("Message 2");
}
}
config1.properties
handlers=java.util.logging.ConsoleHandler
.level= FINE
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
config2.properties
handlers=java.util.logging.ConsoleHandler
.level= FINE
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.XMLFormatter
javac Test.java
java Test
Jan 13, 2014 8:51:20 PM Test main
INFO: Message 1
<?xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
<date>2014-01-13T20:51:20</date>
<millis>1389664280170</millis>
<sequence>1</sequence>
<logger>Test</logger>
<level>INFO</level>
<class>Test</class>
<method>main</method>
<thread>10</thread>
<message>Message 2</message>
</record>
Look at the Documentation of the Logger.getLogger(String name).documentation
it says
If a new logger is created its log level will be configured based on
the LogManager configuration and it will configured to also send
logging output to its parent's handlers. It will be registered in the
LogManager global namespace.
So Even though set a new configuration properties your logger instance have the old configuration
try getting a new instance by calling following line again
logger = Logger.getLogger("new Name");
may be you might have to change the input parameter name differently. or it will return the old logger object
EDIT
Here the sample code i tried
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class LoggingTest {
public static void main(String[] args) {
System.setProperty("java.util.logging.config.file", "config1.properties");
Logger logger = Logger.getLogger(LoggingTest.class.getSimpleName());
logger.info("Message 1");
System.setProperty("java.util.logging.config.file", "config2.properties");
LogManager logManager = LogManager.getLogManager();
try {
logManager.readConfiguration();//logManager.readConfiguration(new FileInputStream(new File("config2.properties")));
} catch (IOException ex) {
Logger.getLogger(LoggingTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(LoggingTest.class.getName()).log(Level.SEVERE, null, ex);
}
logger = Logger.getLogger("NewLogger");
logger.info("Message 2");
}
}
Is there any way to specify Log4J 2.x log4j2.xml file location manually (like DOMConfigurator in Log4J 1.x), without messing with classpath and system properties?
You could use the static method #initialize(String contextName, ClassLoader loader, String configLocation) (see source here) in org.apache.logging.log4j.core.config.Configurator.
(You can pass null for the class loader.)
Be aware that this class is not part of the public API so your code may break with any minor release.
For completeness, you can also specify the location of the configuration file with this system property:
-Dlog4j.configurationFile=path/to/log4j2.xml
If you are using log4j2 and properties are in defined in log4j2.properties file then use this.
-Dlog4j2.configurationFile=file:/home/atul/log4j2.properties
For log4j version 2.12.1, you can find how to reconfigure log4j2 here.
Below is an example
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
File file = new File("C:\\Path for Windows OS\\yourConfig.xml");
LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.setConfigLocation(file.toURI());
Logger log = LogManager.getLogger(YourClass.class);
It seems to me that way of configuring log4j2 is changing with new releases, so you should be aware of that.
In Windows, be aware that you need to use a URI with the log4j.configurationFile property
-Dlog4j.configurationFile=file://C:\path\to\log4j2.xml
Using the LoggerContext allows to setConfigLocation.
File f = new File(this.logConfigFile);
URI fc = f.toURI();
System.out.println("Loading logging config file: " + fc);
Logger l = (Logger) LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
l.getContext().setConfigLocation(fc);
or alternatively
LoggerContext.getContext().setConfigLocation(java.net.URI);
You can initialize like below as well
ConfigurationSource source = new ConfigurationSource(new FileInputStream(log4j file Path));
XmlConfiguration xmlConfig = new XmlConfiguration(source);
Logger logger = (Logger) LogManager.getLogger();
logger.getContext().start(xmlConfig);
In each class you can get logger instance as below
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
private final Logger logger = LogManager.getLogger(ABC.class);
Step: 1 - Get ready with your log4J.xml file with the appender details (Mostly under the resource folder)
Step: 2 - Following code should be added to the configuration class (In the previous log4J we had PropertyConfigurator and now we need to go with LoggerContext)
String log4JFilePath = "file path of your log4J.xml file";
LoggerContext loggerContext = (LoggerContext)LoggerManager.getContext(false);
File file = new File(log4JFilePath);
loggerContext.setConfigLocation(file.toURI());
Step: 3 - Add the following line to utilise the logger in any classes
private static final Logger logger = LogManager.getLogger(yourClassName.class);
logger.info("log here");
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
public class Foo {
public static void main(String[] args) {
Configurator.initialize(null, "src/main/config/log4j2.xml"); //path specify
Logger logger = LogManager.getLogger(APITestToolMain.class);
logger.info("working");
}
}
resource: https://www.baeldung.com/spring-boot-change-log4j2-location
void initializeLogger()
{
try
{
String basepath=checkpath();
File f = new File(basepath+"\\config\\log4j2.properties");
URI fc = f.toURI();
LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.setConfigLocation(f.toURI());
}
catch (Exception e)
{
errorlog="Unable to load logging property:";
System.out.println(errorlog+": "+e.getMessage());
}
}
This is the way I initialize my log4j2 properties file from a different location, so what I simply do is to call the initializeLogger() method in my main method.
And it works perfectly.
Perhaps you need to see what the checkpath() blocks looks like, I added the function below.
String checkpath()
{
String parentpath="";
try
{
URL url=getClass().getProtectionDomain().getCodeSource().getLocation();
File f=new File(url.toURI());
parentpath=f.getParent();
}
catch(Exception ex)
{
//logger.error("unable to retrieve application parent path");
}
return parentpath;
}
It's been a while that I began with log4j; pretty cool logging framework. I've done other type of logging like Console and File Logging. So trying for DB Adapters with mysql for Database logging. Accordingly, I've created following property file named log4j.properties as -
# Define the root logger with appender file
log4j.rootLogger = DEBUG, DB
# Define the DB appender
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
# Set JDBC URL
log4j.appender.DB.URL=jdbc:mysql://localhost:3306/test
# Set Database Driver
log4j.appender.DB.driver=com.mysql.jdbc.Driver
# Set database user name and password
log4j.appender.DB.user=root
log4j.appender.DB.password=
# Set the SQL statement to be executed.
log4j.appender.DB.sql=insert into log(date,level,message) values("%d","%p","%m")
# Define the layout for file appender
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
And used it in a test class in following way -
public class DBLoggerTest {
static Logger logger;
public DBLoggerTest() {
//System.setProperty("log4j.configuration", "log4j.properties");
logger = Logger.getLogger(DBLoggerTest.class.getName());
}
public static void main(String[] args) {
new DBLoggerTest();
logger.info("This is a test info");
logger.error("This is an error messsage");
}
}
But I got following error -
log4j:WARN No appenders could be found for logger (com.satyam.logger.test.DBLoggerTest).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Any help please...?
If you are using mysql. create a file log4j.properties. This worked for me.
Put this at the root folder of you application. i.e root of all packages. I also do have a table logs with fields id,date,user, message and class.
log4j.rootLogger=DEBUG,DB
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DB.URL=jdbc:mysql://localhost:3306/test
log4j.appender.DB.user=root
log4j.appender.DB.password=root
log4j.appender.DB.sql=INSERT INTO logs(date, user, message,class) VALUES ('%d{yyyy-MM-dd HH:mm:ss}', '%X{User}','%m','%c')
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=INSERT INTO logs (date, user,message,class) VALUES ('%d{yyyy-MM-dd HH:mm:ss}', '%X{User}','%m','%c')
log4j.category.ke.co=ERROR
log4j.category.ke.co.appender-ref=DB
Then use it as follows.
package com.zeddarn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
public class MySQLDatabaseConnector {
static ThreadLocal<Connection> connection = new ThreadLocal<Connection>();
private static Logger logger = Logger.getLogger(MySQLDatabaseConnector.class);
public static Connection getDBConnection() {
//check if a mysql connection already exits. This is to avoid reconnecting
if (connection.get() == null) {
try {
//loading the mysql driver. This means you also have to add mysql libary. You can add manually or via maven
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
//do something to deal with the error of missing mysql driver e.g notification to the user.
MDC.put("User", "loggeduser");
logger.error(e.getMessage());
MDC.getContext().clear();
}
try {
connection.set(DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"));
} catch (SQLException e) {
MDC.put("User", "loggeduser");
logger.error(e.getMessage());
MDC.getContext().clear();
}
}
return connection.get();
}
public static void main(String args[]) {
MDC.put("User", "loggeduser");
logger.error("message from exception.getMessage() method");
MDC.getContext().clear();
}
}