Including classpath resource in external log4j configuration - log4j2

I use external log4j configuration and load it in servlet context listener using org.apache.logging.log4j.core.config.Configurator
I would like to reference some application properties (like application version) that are generated on build time.
Here is what I would like to do:
/external-folder/log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:xi="http://www.w3.org/2001/XInclude"
monitorInterval="60">
<xi:include href="log4j2-properties.xml" />
<Appenders>
<Console name="stdout" target="SYSTEM_OUT">
<PatternLayout pattern="%d %5p %t [${app-version}] %m (%F:%L) %n" />
</Console>
</Appenders>
<!-- ... -->
</Configuration>
log4j2-properties.xml
is supposed to be a classpath resource, #version# is filtered by gradle.
<?xml version="1.0" encoding="UTF-8"?>
<Properties>
<Property name="app-version">#version#</Property>
</Properties>
However this approach doesn't work. I can xinclude only resource from the same folder as top level log4j.xml
How can I solve my problem?
(I know how to do this using logback, but I would like to upgrade to log4j2)

Related

log4j2 TimeBasedTriggeringPolicy not working as expected

I have configured the log4j2.xml file in such a way that application.log file will be created and it should be rollover daily.
<?xml version="1.0" encoding="UTF-8"?>
<!-- ===================================================================== -->
<!-- Log4j2 Configuration -->
<!-- ===================================================================== -->
<Configuration status= "INFO">
<!-- Common properties used in all appenders -->
<Properties>
<Property name="logBaseDirectory">/apps/wsserver/8.5/bpm/logs/log4j/sbl</Property>
<Property name="logPattern">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{1} %X{transaction.id} %m%n</Property>
<Property name="maxFileAge">90d</Property>
</Properties>
<!-- Define required appenders -->
<Appenders>
<!-- ============================================================================================================================================ -->
<!-- log4j 1.x to 2.x migratoin steps -->
<!-- DailyRollingFileAppender rolling file appender is no longer availble in log4j2. So we need to use RollingFile with TimeBasedTriggeringPolicy -->
<!-- Right most value in filePattern will be considered as Interval for TimeBasedTriggeringPolicy rolling -->
<!-- Orignal log file will be application.log and archive will be application-20200917.log.zip - Auto compression of file -->
<!-- Remove the all archived logs which are older than 90 days -->
<!-- ============================================================================================================================================ -->
<RollingFile name="application" fileName="${logBaseDirectory}/application.log" filePattern="${logBaseDirectory}/application-%d{yyyy-MM-dd}.log.zip">
<PatternLayout pattern="${logPattern}"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy />
<CronTriggeringPolicy />
</Policies>
<DefaultRolloverStrategy>
<Delete basePath="${logBaseDirectory}" maxDepth="1">
<IfFileName glob="application-*.log.zip" />
<IfLastModified age="${maxFileAge}" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<!-- Define the list of loggers required -->
<Loggers>
<logger name="MediationServices" level="TRACE" additivity="false">
<appender-ref ref="application" />
</logger>
<root level="TRACE" additivity="false">
<appender-ref ref="application" />
</root>
</Loggers>
</Configuration>
But in JVM, applicatoin.log file is getting rollover after 10MB and if three times it is rolled, the first file is getting overwritten. That means at any point of time i am having application.log and application-2020-10-16.log.zip.
Why log4j2 (v2.13) is rolling over the files for every 10MB even though configured as daily? Any pointers identifying issue in log4j2 configuration is much apricated.
Issue has been identified. AS <SizeBasedTriggeringPolicy /> is defined in configuration file, log4j2 is considering 10MB default value as file size and getting rollover. After removing this tag, issue has been resolved.

Log4j2 not logging statements from WAR and Non-EJB jars in an EAR

I have an unpacked EAR deployed at $JBOSS_HOME/standalone/deployments in Wildfly-8.2.0.Final AS. It contains unpacked WAR and application jar files.
HelloWorldEar-0.0.1-SNAPSHOT.ear
-HelloWorldServlet-0.0.1-SNAPSHOT.war
-lib
-META-INF
-aspectjrt-1.8.6.jar
-HelloWorldAnnotation-0.0.1-SNAPSHOT.jar
-HelloWorldAspect-0.0.1-SNAPSHOT.jar
-HelloWorldCommonLib-0.0.1-SNAPSHOT.jar
-HelloWorldEJB-0.0.1-SNAPSHOT.jar
-log4j2.xml
lib folder of EAR contains log4j2 related APIs for providing logging feature.
lib
-commons-logging-1.2.jar
-HelloWorldLog4jPlugin-0.0.1-SNAPSHOT.jar (Jar containing custom log4j2 plugins)
-log4j-api-2.4.1.jar
-log4j-core-2.4.1.jar
-log4j-jcl-2.4.1.jar
-log4j-web-2.4.1.jar
I am initializing log4j2 configuration by initializing log4j2.xml using in a startup singleton bean in HelloWorldEJB-0.0.1-SNAPSHOT.jar.
String path = System.getProperty("jboss.home.dir")
+ "/standalone/deployments/HelloWorldEar-0.0.1-SNAPSHOT.ear/log4j2.xml";
ConfigurationSource source;
File configFile = new File(path);
try {
source = new ConfigurationSource(new FileInputStream(configFile), configFile);
Configurator.initialize(null, source);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
log4j2.xml content
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="trace">
<Appenders>
<RollingFile name="SERVER_FILE" fileName="${sys:LOGS}/sample.log" filePattern="${sys:LOGS}/sample.log.%i" append="true">
<PatternLayout>
<pattern>%d %-5p [%c{1}] [EventId: %e] [%t] %m%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="500 KB" />
</Policies>
<DefaultRolloverStrategy max="5"/>
</RollingFile>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout>
<pattern>%d{ABSOLUTE} %-5p [%c{1}] %m%n</pattern>
</PatternLayout>
</Console>
</Appenders>
<Loggers>
<Logger name="com.test.prototype.log4j" level="debug">
<AppenderRef ref="SERVER_FILE"/>
</Logger>
<Root level="debug" additivity="false">
<AppenderRef ref="CONSOLE"/>
</Root>
</Loggers>
</Configuration>
All the sub-packages and classes are defined under the package com.test.prototype.log4j.
Log statements added in the classes of HelloWorldEJB-0.0.1-SNAPSHOT.jar gets logged in the log file.
My issue is that 1. log statements from other application jars and WAR are not getting logged into the log file.
2. Logging not working through commons-logging API though required system parameters for log4j2 is added.
System.setProperty("org.apache.commons.logging.Log",
"org.apache.commons.logging.impl.Log4JLogger");
I have tried adding the class-path in the application jars and below listener in the web.xml of WAR file but nothing worked.
org.apache.logging.log4j.web.Log4jServletContextListener
I need to have log4j2.xml under EAR and it should server for the all the application jars and WARs added in the EAR. Could anyone please help me about how to resolve this issue.
Have you tried specifying the log4j2.xml config file location with system property -Dlog4j.configurationFile=path/to/log4j2.xml?
I suspect that the way you're initializing log4j now is not visible from other WARs.
If this fails, please raise this issue on the log4j2 Jira issue tracker. https://issues.apache.org/jira/browse/LOG4J2

log4j2 to chainsaw hello world not working... what am I doing wrong?

I'm trying to stream a basic hello world log message to show up in chainsaw from log4j2. I don't care if it uses "Zeroconf" or not, I just want something that works. I know that my test program is logging messages since they show on the console, and I know it's finding my config file because I can change the format of the messages that get printed in the console, but that's all I know.
My config file (containing various failed guesses):
<?xml version="1.0" encoding="UTF-8"?>
<configuration advertiser="org.apache.logging.log4j.core.net.MulticastDNSAdvertiser">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %m%n"/>
</Console>
<File name="testFile" fileName="logs/test.log" bufferedIO="false" advertiseURI="file://localhost/home/matt/code/ade/logs/test.log" advertise="true">
<XMLLayout />
</File>
<SocketAppender name="socketTest" host="localhost" immediateFlush="true" port="4560" protocol="TCP" advertiseURI="http://localhost" advertise="true">
<XMLLayout />
</SocketAppender>
</appenders>
<loggers>
<root level="TRACE">
<appender-ref ref="Console"/>
<appender-ref ref="testFile"/>
<appender-ref ref="socketTest"/>
</root>
</loggers>
</configuration>
I've tried various combinations of: including jmdns.jar on the classpath, restarting chainsaw at various points, and getting frustrated, but nothing has helped.
Any ideas?
Edit: I figured out why it couldn't read the log files I was saving to disk, (I hadn't been using XMLLayout) so I've updated the question to reflect that I now only need to get streaming working.
The 'advertiser' uses the log4j2 plugin mechanism, so you must provide the 'name' defined on the Advertiser in the configuration - not the fully-qualified class name.
The log4j2 advertisement mechanism currently supports advertisement of FileAppenders and SocketAppenders. However, Chainsaw only supports discovery of log4j2 FileAppenders which are advertised with a PatternLayout. XMLLayout support will show up in the near future.
The latest developer snapshot of Chainsaw must be used in order to leverage log4j2's advertiser mechanism. Chainsaw tarball and DMG available at: http://people.apache.org/~sdeboy/
Chainsaw will discover the advertised fileappender configuration and parse (and tail if you get the latest Chainsaw developer build) the log file - no Chainsaw configuration required.
Note, you need to use a PatternLayout, and JMDNS must be on the classpath of the application using this appender configuration.
Here is an example Log4j2 -appender- configuration that will advertise a fileappender configuration:
<?xml version="1.0" encoding="UTF-8"?>
<configuration advertiser="multicastdns">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %m%n"/>
</Console>
<File name="testFile" fileName="logs/test.log" bufferedIO="false" advertiseURI="file:///localhost/home/matt/code/ade/logs/test.log" advertise="true">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %m%n"/>
</File>
</appenders>
<loggers>
<root level="TRACE">
<appender-ref ref="Console"/>
<appender-ref ref="testFile"/>
</root>
</loggers>
</configuration>
Once you have started your app that is using the appender
configuration, open the 'Zeroconf' tab in Chainsaw.
You should see a row with your appender's name (assuming you added
jmdns to the classpath for the app using the fileappender
configuration).
You can click 'Autoconnect' if you'd like to always start Chainsaw
with this configuration if it is available.
Next, double-click
on the row with the appender name and Chainsaw will start parsing and tailing your log file.
The advertised URL provided in your file appender
configuration must be accessible network-wise to Chainsaw (looks like you are working
locally with Chainsaw and your fileappender, so file:/// paths will
work fine - note the three slashes).
Chainsaw will work best if there are delimiters around each field - square brackets, dashes, etc. as long as that character won't be present in the field you are delimiting.

netbeans glassfish hibernate log4j2

I have a simple Netbeans 7.1.2 (NON MAVEN) project that use glassfish 3.1 server for testing.
I created a log4j2.xml file and placed it on the classpath
here it is
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug"/>
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} [%t] %-5p %c{1} - %m%n"/>
</layout>
</appender>
<appender name="rolling-file" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="c:\tmp\Program-Name.log"/>
<param name="MaxFileSize" value="500KB"/>
<param name="MaxBackupIndex" value="4"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %l - %m%n"/>
</layout>
</appender>
<logger name="org.hibernate">
<level value="info" />
</logger>
<root>
<priority value ="debug" />
<appender-ref ref="console" />
<appender-ref ref="rolling-file" />
</root>
</log4j:configuration>
the project uses hibernate to store data from a web service to a database.
However I am not able to log anything. I can see the logs of hibernate into the Netbeans IDE but I cannot see the created on the filesystem file.
I have this error when calling the web service
SEVERE: ERROR StatusLogger Unknown object "logger" of type org.apache.logging.log4j.core.config.LoggerConfig is ignored
SEVERE: ERROR StatusLogger root contains an invalid element or attribute "priority"
SEVERE: ERROR StatusLogger Unknown object "root" of type org.apache.logging.log4j.core.config.LoggerConfig is ignored
could someone pls help or give some advice I googled and stackoverflowed but without chance.
Paolo
I think that your log4j2.xml file is mixed with the old log4j style xml.
I'm having the same trouble as you when it comes to appending hibernate log to my application's log file. But I think that I can help with the logger error.
Try this file instead (and note the changes that I made):
<?xml version="1.0" encoding="UTF-8" ?>
<configuration name="SOME_PROJ_NAME" status="OFF">
<appenders>
<RollingFile name="rolling-file" fileName="c:/tmp/Program-Name.log" filePattern="c:/tmp/$${date:yyyy-MM}/Program-Name-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<pattern>%d{ABSOLUTE} [%t] %-5p %c{1} - %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="6" modulate="true"/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>
</appenders>
<loggers>
<root level="info"
<appender-ref ref="rolling-file"/>
</root>
<logger name="org.hibernate level="info">
<appender-ref ref="rolling-file"/>
</logger>
</loggers>
</configuration>
It is quite similar to the one that I'm using. Note that this file should be on classpath for log4j2 auto configuration to kick in.
The most important thing you should do when using the net to configure log4j2 is that you're looking at log4j2 and not log4j style configuration.
I suggest that you look in http://logging.apache.org/log4j/2.x/ for further info. They have a good downloadable pdf that you can check out.
In addition, check out my question about a similar problem.

error in persistence.xml

I am trying to deploy a simple EJB project onto Jboss 7.1.1. I have a separate installation of H2 database.
So I changed the standalone.xml as follows:
<subsystem xmlns="urn:jboss:domain:datasources:1.0">
<datasources>
<datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
<connection-url>jdbc:h2:tcp://localhost/~/test</connection-url>
<driver>h2</driver>
<security>
<user-name>sa</user-name>
<password>sa</password>
</security>
</datasource>
<drivers>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
</drivers>
</datasources>
</subsystem>
Now I have also edited the persistence.xml to match the names in the standalone.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="scube" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.sample.model.Property</class>
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.max_fetch_depth" value="3" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Eclipse, points an error at line: java:jboss/datasources/ExampleDS
Error is as follows:
cvc-complex-type.2.4.a: Invalid content was found starting with element 'jta-data-source'. One of '{"http://java.sun.com/xml/ns/persistence":class, "http://java.sun.com/
xml/ns/persistence":exclude-unlisted-classes, "http://java.sun.com/xml/ns/persistence":shared-cache-mode, "http://java.sun.com/xml/ns/persistence":validation-mode,
"http://java.sun.com/xml/ns/persistence":properties}' is expected.
I searched for similar errors and all the resolutions said that either the order of xml elements were important, which I checked or the jndi name should match with standalone.xml, which does match.
Can someone help me with this?
The right order of XML elements (according to schema document) is:
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
<class>com.sample.model.Property</class>

Resources