My programs stops log in files just by replacing:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
with
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
I'm using : OracleJdk8, log4j-core-2.17.1 and slf4j-sample-2.0.0-alpha6
Please find bellow my log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="log-path">C:/path/to/logfile</Property>
</Properties>
<Appenders>
<Console name="console-log" target="SYSTEM_OUT">
<PatternLayout pattern="[%-5level] %d{dd/MM/yyyy HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
<RollingFile name="functional-log" fileName="${log-path}/functional.log" filePattern="${log-path}/functional-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{dd/MM/yyyy HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
<LevelRangeFilter minLevel="INFO" maxLevel="INFO" onMatch="ACCEPT" onMismatch="DENY" />
</RollingFile>
<RollingFile name="technical-1-log" fileName="${log-path}/technical.log" filePattern="${log-path}/technical-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{dd/MM/yyyy HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
<LevelRangeFilter minLevel="DEBUG" maxLevel="TRACE" onMatch="ACCEPT" onMismatch="DENY" />
</RollingFile>
<RollingFile name="technical-2-log" fileName="${log-path}/technical.log" filePattern="${log-path}/technical-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{dd/MM/yyyy HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
<LevelRangeFilter minLevel="WARN" maxLevel="WARN" onMatch="ACCEPT" onMismatch="DENY" />
</RollingFile>
<RollingFile name="error-log" fileName="${log-path}/error.log" filePattern="${log-path}/error-%d{yyyy-MM-dd}.err">
<PatternLayout>
<pattern>[%-5level] %d{dd/MM/yyyy HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="x.y.z" level="ALL" additivity="false">
<appender-ref ref="console-log" level="ALL" />
<appender-ref ref="functional-log" level="INFO" />
<appender-ref ref="technical-1-log" level="TRACE" />
<appender-ref ref="technical-2-log" level="WARN" />
<appender-ref ref="error-log" level="ERROR" />
</Logger>
<Root level="TRACE" additivity="false">
<AppenderRef ref="console-log" />
</Root>
</Loggers>
</Configuration>
By this configuration, I'd like to log :
"ERROR" and "FATAL" in error.err file.
"TRACE", "DEBUG" and "WARN" in technical.log file.
"INFO" in functional.log file.
Could you please indicate me the right way to use slf4j import to still logging in RollingFile?
Knowing that org.slf4j.Logger.fatal() method doesn't exist :(
Thank you so much for you help!
The log error messages are getting printed to all the log files instead of the error file. Not sure what i have missed in the configuration. Can anyone check and let me know
I tried all permutations and combinations but nothing seems to be working.
I think i am missing some configuration but not sure what it is.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<Properties>
<Property name="LOG_PATTERN">
%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [%X{id}] ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
</Property>
</Properties>
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
<RollingFile name="ROOTLOGS" fileName="${sys:LOG_DIR}bot.log"
filePattern="${sys:LOG_DIR}bot-%d{yyyy-MM-dd}-%i.log.gz" >
<PatternLayout>
<pattern>%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}- [%-5level] : %m%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="10" />
<ThresholdFilter level="DEBUG"/>
</RollingFile>
<RollingFile name="ERRORLOGS" fileName="${sys:LOG_DIR}boterror.log"
filePattern="${sys:LOG_DIR}boterror-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout>
<pattern>%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="10" />
<ThresholdFilter level="ERROR"/>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.org.bot" level="DEBUG" additivity="false">
<appender-ref ref="ERRORLOGS" />
<appender-ref ref="ROOTLOGS" />
</Logger>
<Root level="info" additivity="false">
<AppenderRef ref="ConsoleAppender"/>
<AppenderRef ref="ROOTLOGS" />
<AppenderRef ref="ERRORLOGS" />
</Root>
</Loggers>
</Configuration>
Expectation is that error messages should only get printed to boterror.log file and normal application messages should get printed to bot.log.
DENY error messages from ROOTLOGS.
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
<RollingFile name="ROOTLOGS" fileName="${sys:LOG_DIR}bot.log"
filePattern="${sys:LOG_DIR}bot-%d{yyyy-MM-dd}-%i.log.gz" >
<PatternLayout>
<pattern>%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}- [%-5level] : %m%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="10" />
<ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="ACCEPT"/>
</RollingFile>
<RollingFile name="ERRORLOGS" fileName="${sys:LOG_DIR}boterror.log"
filePattern="${sys:LOG_DIR}boterror-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout>
<pattern>%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="10" />
<ThresholdFilter level="ERROR"/>
</RollingFile>
</Appenders>
This is what finally did the trick. Whatever sazzad has suggested + i need to add threshold filter to ERRORLOG without which normal logs were also getting added to it.
This is the final configuration which is working as per my expectations
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<Properties>
<Property name="LOG_PATTERN">
%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [%X{id}] ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
</Property>
</Properties>
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
<RollingFile name="ROOTLOGS" fileName="${sys:LOG_DIR}bot.log"
filePattern="${sys:LOG_DIR}bot-%d{yyyy-MM-dd}-%i.log.gz" >
<PatternLayout>
<pattern>%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}- [%-5level] : %m%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="10" />
<ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="ACCEPT"/>
</RollingFile>
<RollingFile name="ERRORLOGS" fileName="${sys:LOG_DIR}boterror.log"
filePattern="${sys:LOG_DIR}boterror-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout>
<pattern>%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="10" />
<ThresholdFilter level="ERROR"/>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.org.bot" level="DEBUG" additivity="false">
<appender-ref ref="ERRORLOGS" />
<appender-ref ref="ROOTLOGS" />
</Logger>
<Root level="info" additivity="false">
<AppenderRef ref="ConsoleAppender"/>
<AppenderRef ref="ROOTLOGS" />
<AppenderRef ref="ERRORLOGS" />
</Root>
</Loggers>
</Configuration>
I am not interested in printing logs to console, only to file.
my current Log4j2.xml configuration doesn't support this unless I am configuring 'level=" OFF"' but then it doesn't write to both, file and console.
how do I configure the logger to write only to file?
already tried to comment out the tag and to comment out the "appenderRef" tag inside the "Logger" tag
the log4j2.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<Configuration>
<Appenders>
<RollingFile name="vertx_file" append="true"
fileName="/var/log/vertx.log"
filePattern="/var/log/vertx/$${date:yyyy-MM}/vertx-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout pattern="%d{ISO8601} %-5p %c:%L - %m%n" />
<Policies>
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="5MB" />
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
<Console name="STDOUT" target="SYSTEM_OUT">
<!-- <LogStashJSONLayout/> -->
<PatternLayout pattern="%d{ISO8601} %-5p %c:%L - %m%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="com.service.vertex" level="OFF" >
<!-- <AppenderRef ref="vertx_rollingFile" /> -->
<!-- <AppenderRef ref="vertx_socket" /> -->
<!-- <AppenderRef ref="STDOUT" /> -->
<AppenderRef ref="vertx_file" />
</Logger>
<Logger name="org.mongodb.driver" level="OFF">
<AppenderRef ref="vertx_rollingFile" />
<AppenderRef ref="vertx_socket" />
<AppenderRef ref="STDOUT" />
<AppenderRef ref="vertx_file" />
</Logger>
<Root level="INFO">
<AppenderRef ref="vertx_socket" />
<!--<AppenderRef ref="STDOUT" />-->
<AppenderRef ref="vertx_file" />
</Root>
</Loggers>
</Configuration>
the log:
Apr 03, 2019 2:02:35 PM com.service.vertex.dao.UsersCollection
INFO: {"response_code":551,"description":"INVALIDATE SESSION ERROR: null","log_origin":"system","id":"ERROR (57) 14:02:35:050","time":"2019-04-03 14:02:35:050","host_name":"pc","server_port":"444","level":"ERROR","verticle":"admin","remote_address":"172.15.333.21"}
still printing to console
Comment the below in the config and try
<Console name="STDOUT" target="SYSTEM_OUT">
<!-- <LogStashJSONLayout/> -->
<PatternLayout pattern="%d{ISO8601} %-5p %c:%L - %m%n" />
</Console>
and the appenders
<AppenderRef ref="STDOUT" />
We have a situation where the server is in Germany and we're based in the UK. We want the log4net logs to show a timestamp that is GMT, but I can't work out how or if it's possible to add an hour to the time being written to the log file.
This is our current config:
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="logs\\" />
<datePattern value="dd.MM.yyyy'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="50" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-dd-MM HH:mm:ss.fff} %-5level - %message%newline" />
</layout>
</appender>
I found some references online to an "hourOffset", but this doesn't seem to work and never appears in the log4net documentation.
Any advise here would be welcome.
Use utcdate instead of d (or date). See also the documentation.
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%utcdate{yyyy-dd-MM HH:mm:ss.fff} %-5level - %message%newline" />
</layout>
My Visual Studio Solution contains:
[DLL] Sol.DataAccess (NHibernate sessionManager)
[DLL] Sol.Core (Models and Repository)
[MVC] Sol.WebMvc (Controler, View)
All my application contains are (nhibernate.dll [v3.0] and log4net.dll[v1.2.10])
I have 3 configs:
web.config:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" requirePermission="false" />
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
</configSections>
</configuration>
nhibernate.config:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="...">
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string_name">...</property>
<property name="adonet.batch_size">10</property>
<property name="show_sql">true</property>
<property name="generate_statistics">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="use_outer_join">true</property>
<property name="max_fetch_depth">2</property>
<property name="command_timeout">60</property>
<property name="adonet.batch_size">25</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name="current_session_context_class">web</property>
<property name="cache.use_query_cache">true</property>
<property name="cache.provider_class">NHibernate.Caches.SysCache2.SysCacheProvider, NHibernate.Caches.SysCache2</property>
<mapping assembly="..."/>
</session-factory>
</hibernate-configuration>
and log4net.config:
<log4net>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<!--for release-->
<!--<bufferSize value="10" />-->
<!--for debug-->
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=xxxxx; Initial Catalog=xxxx; User Id=xxxx; Password=xxxxx; App=xxxx" />
<commandText value="INSERT INTO Logs ([Application],[Host],[User],[Date],[Thread],[Level],[Operation],[Logger],[Message],[Exception]) VALUES (#app, #hostName, #userName, #log_date, #thread, #log_level, #operation, #logger, #message, #exception)" />
<parameter>
<parameterName value="#app" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="xxxx" />
</layout>
</parameter>
<parameter>
<parameterName value="#hostName" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{hostName}" />
</layout>
</parameter>
<parameter>
<parameterName value="#userName" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{userName}" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="#operation" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{Operation}" />
</layout>
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="Logs/Logs.txt"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<appender name="Console" type="log4net.Appender.AspNetTraceAppender">
<!--A1 uses PatternLayout-->
<layout type="log4net.Layout.PatternLayout">
<!--Print the date in ISO 8601 format-->
<conversionPattern value="%date [%thread] %-5level %logger %ndc - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="Console"/>
<appender-ref ref="FileAppender"/>
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
Global.cs:
protected void Application_Start()
{
...
// Configuration
#region log4net
// log4net.config
System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath("~/log4net.config"));
if (fi != null && fi.Exists)
{
// Code that runs on application startup
log4net.Config.XmlConfigurator.Configure(fi);
}
// web.config
//log4net.Config.XmlConfigurator.Configure();
// set properti hostName
log4net.GlobalContext.Properties["hostName"] = Dns.GetHostName();
#endregion
#region NHibernate
//HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
var factory = NHibernateSessionManager.ConfigureFromFile(Server.MapPath("~/hibernate.config"));
#endregion
}
in my test controller i have:
public class TestController : BaseController
{
[NHibernateSession]
public ActionResult Index()
{
Logger.Error("fake error", new Exception());
}
}
In my log file - Logs/Logs.txt:
2011-03-11 18:19:23,097 [8] ERROR System.Web.Mvc.Controller [(null)] - fake error
System.Exception: Exception of type 'System.Exception' was thrown.
QUESTION:
Why log4net doesn't log NHibernate information (info, debug ....)
Aren't the versions of these dlls compatible?
I have create an empty ASP.Net MVC3 project. and loss much time trying to fix this issue.
And I find VS2010 bug. Visual Studio 2010 don't copy dll's in bin when you refer it in project.
I put log4net.dll manual in my bin folder and work fine. (Interesting thing is that Logger.Error("fake error") work fine without log4net.dll in bin folder ...)
First off: you speak of "log4net.config", but you don't include that anywhere. The way you configure it in web.config, you should actually include a section called <log4net> inside your web.config, not as a separate file.
If you don't want it in your web.config, you can remove the log4net related sections altogether and add the following line to yur global.asax.cs:
log4net.Config.XmlConfigurator.ConfigureAndWatch(
New FileInfo(Server.MapPath("~/yourreleativepath/log4net.config")))
Also, possibly you miss the priority setting, not entirely sure this helps, but give it a try:
<root>
<priority value="DEBUG"/>
<appender-ref ref="Console"/>
<appender-ref ref="FileAppender"/>
<appender-ref ref="AdoNetAppender"/>
</root>
Also, to finetune (because you'll get a lot messages), use something like this:
<logger name="NHibernate.SQL">
<level value="DEBUG"/>
</logger>
<logger name="NHibernate">
<level value="WARN"/>
</logger>
On nhibernate.info you'll find a full example.