How to set LogLevel to error in log4net for hangfire - asp.net-mvc

We have a web application and we are using log4net for logging. Recently I installed hangfire and now my log table (sqlserver db) is full of log enteries from hangfire. I want to minimise this to error and exceptions only. I believe I can set it by setting LogLevel to error but where exactly I need to do that.
Thanks

Add this logger to your web.config (log4net section)
<logger additivity="false" name="Hangfire">
<level value="ERROR" />
<appender-ref ref="HangfireLoggerAppender" />
</logger>

Adding to what #Martino mentioned above here is the exact location to add that tag in log4net section:
<log4net debug="true">
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file type="log4net.Util.PatternString" value="%property{LogFileName}" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
<logger additivity="false" name="Hangfire">
<level value="ERROR" />
<appender-ref ref="HangfireLoggerAppender" />
</logger>
</log4net>

Related

Generate log file daily using log4j2.xml and how to use SNMP appender in log4j2.xml

1)I want to generate the log file on daily basis using log4j2.xml. I am using the RollingFile appender tag to achieve the same.However, it is appending the logs on the same file.
<RollingFile name="FrameworkAppender" filePattern="${jboss.server.home.dir}/xyz_app-%d{yyyy-MM-dd}-%i.log" >
<PatternLayout>
<Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
</PatternLayout>
<LevelRangeFilter minLevel="ERROR" maxLevel="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
<Policies>
<CronTriggeringPolicy schedule="0 0 0 * * ?" />
<SizeBasedTriggeringPolicy size="250 MB" />
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
2)Below is the category tag we have used in log4j.xml ,i want to know what is the equivalent of category tag in log4j2.xml ?
<category name="biz.theXYZ" additivity="false">
<level value="INFO" />
<appender-ref ref="FrameworkAppender" />
<appender-ref ref="ConsoleAppender" />
</category>
3)How to define SNMPTrapAppender with all the properties in log4j2?
<appender name="TRAP_LOG_APPENDER" class="org.apache.log4j.ext.SNMPTrapAppender">
<param name="ImplementationClassName" value="org.apache.log4j.ext.JoeSNMPTrapSender"/>
<param name="EnterpriseOID" value="1.3.6.1.4.1.2854.1"/>
<param name="ApplicationTrapOID" value="1.3.6.1.4.1.24.12.10.22.64"/>
<param name="ManagementHost" value="127.0.0.1"/>
<param name="ManagementHostTrapListenPort" value="162"/>
<param name="LocalIPAddress" value="127.0.0.1"/>
<param name="LocalTrapSendPort" value="161"/>
<param name="GenericTrapType" value="6"/>
<param name="SpecificTrapType" value="12345678"/>
<param name="CommunityString" value="public"/>
<param name="ForwardStackTraceWithTrap" value="true"/>
<param name="Threshold" value="INFO"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d,%p,[%t],[%c],%m%n"/>
</layout>
</appender>
you should add
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
For the second question, the equivalent in log4j2 is:
<Loggers>
<Logger name="biz.theXYZ" level="info">
<AppenderRef ref="FrameworkAppender"/>
<AppenderRef ref="ConsoleAppender"/>
</Logger>
</Loggers>
Make sure to include the FrameworkAppender and ConsoleAppender in the Appenders section of your log4j2 file.

OpenJPA + Log4j2

Having problem with integrating OpenJPA with log4j2.
OpenJPA + log4j worked fined
<appender name="OPENJPA_LOG" class="org.apache.log4j.RollingFileAppender">
<param name="maxFileSize" value="5MB" />
<param name="maxBackupIndex" value="10" />
<param name="file" value="./logs/openjpa.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n" />
</layout>
</appender>
<logger name="openjpa.jdbc.SQL" additivity="false">
<level value="TRACE" />
<appender-ref ref="OPENJPA_LOG" />
</logger>
But it is not working with log4j2.
<RollingFile name="OPENJPA_LOG" fileName="./logs/openjpa.log"
append="true" filePattern="./logs/openjpa.%i.log.gz"
ignoreExceptions="false">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} - %c [%thread] - %m%n</Pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10MB" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile>
<Logger name="openjpa.jdbc.SQL" level="TRACE" additivity="false" >
<AppenderRef ref="OPENJPA_LOG" />
</Logger>
How to fix it.
If you still have issues with this you have to double check that in the persistence.xml you set <property name="openjpa.Log" value="slf4j"/>.
Indeed open jpa is not compatible with log4j2 natively so if you use <property name="openjpa.Log" value="log4j"/> you will run into a java.lang.ClassNotFoundException: org.apache.log4j.Priority.
Once openjpa logs are route properly to slf4j it is ok. I hope your application use sllf4j.
Be sure to use proper versions of log4j2 slf4j and bridge and remove all previous log4j1.x and old slf4j dependencies.

Asp.net MVC log4net with lockingModel makes session lost

I get a MVC website and with the log4net to record the log.
In the web application, I store the user information in session, add log some information after executing one operation. Then the session lost when I returned to the home page(just type the url of the home page).
I am sure that the session lost which has no relation to the "Response.Redirect()" or something else, because I test the application and found it will recover after I comment the lockingModel property which value is "log4net.Appender.FileAppender+MinimalLock" in log4net config file.
Below is the configuration:
<?xml version="1.0"?>
<log4net debug="true">
<appender name="AllInfoRollingAppender" type="log4net.Appender.RollingFileAppender">
<file value="bin\\Log\\AllInfo-UniqueBlog-" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<appendToFile value="true" />
<staticLogFileName value="false" />
<rollingStyle value="Composite" />
<datePattern value="yyyy-MM-dd.LOG" />
<maximumFileSize value="1M" />
<maxSizeRollBackups value="4" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger: %message%newline%exception" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="AllInfoRollingAppender" />
</root>
</log4net>
So I think the "lockingModel" property in log4net config cause this error, but i don't know the reason, and it will not throw any error there, does anyone encounter this? I found it is inconceivable because this shouldn't cause this issue.
Your question is totally not readable. However I have to things you can check. If your session is lost, do you log before or after the Session.Redirec(). If you log after the session redirect, your code is never hit. The redirect ends your current thread. Next thing you can enable log4net debugging:
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
...
</configuration>
If something bad happens in log4net, you will see it in the logs.

Where is the log file in log4net?

I've got the following entries in my Web.config file in an asp.net mvc application:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
...
</configSections>
<log4net>
<appender name="PublicAccessAppender" type="log4net.Appender.RollingFileAppender">
<datePattern value="'C:\Users\my_user_name\Documents\Temp\logs\public-access.'yyyy-MM-dd'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="5" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="PublicAccessAppender" />
</root>
</log4net>
...
</configuration>
I hope it's pretty self-explanatory what I'm trying to achieve, but when I run the application (hosted in IIS), I get no log file. FWIW, the directory hierarchy exists up to Temp folder, and I'd like log4net to generate the rest of the directories/files in the path.
I've added the log4net nuget package to my application, and I'm logging with the INFO level.
What am I missing here?
I think you can't put full path into datePattern, there must be just YYYYmmdd and things like that. Put the file path into file element:
<file value="C:\Users\my_user_name\Documents\Temp\logs\public-access.log" />
<datePattern value="yyyyMMdd" />
<preserveLogFileNameExtension value="true" />
The last element forces to put datePattern before the .log extension which was probably your original goal..
Here's the working appender configuration:
<appender name="PublicAccessAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\temp\my_user_name\Documents\Temp\logs\app.log" />
<datePattern value=".yyyy-MM-dd" /><!-- can be omitted as it's the default datePattern value -->
<rollingStyle value="Date" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
Note to readers struggling with log4net configuration: asp.net hosted in IIS pretty much has 0 write permssions, so the issue you're most likely struggling with is that your web app simply doesn't have permission to write to the log file.
That's what was happening for me, and I noticed it by inspecting the contents of log4net.LogManager.GetRepository().ConfigurationMessages in the debugger after calling .Configure().
I followed this post to give my web app the necessary persmissions to write to the log file (namely Read/Write/Modify).

How to enable Common.Logging.Log4Net

I am trying to enable Common.Logging.Log4Net to write all types of logs to a log file. The tutorials make it look so simple but I don't know what I am doing wrong. These are the steps I am taking:
Create a new ASP.NET MVC empty project
Install the "Common Logging Log4Net 1211" NuGet package
Add the following lines to the default web.config:
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
<arg key="configType" value="INLINE" />
</factoryAdapter>
</logging>
</common>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="FileAppender" />
</root>
<appender name="FileAppender" type="log4net.Appender.FileAppender" >
<param name="File" value="C:\Users\MyName\Downloads\log.txt" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
Make sure the app. pool identity account has RW access to the path where I am trying to save the log file.
Throw a random exception from code for testing purposes.
Am I missing anything? Is there a way I can debug log4net? Please help this poor soul. Thank you.
The issue was related to the NuGet package for "Common.Logging.Log4Net" changing the name of the assembly. This actually fixed it (plesae note the new assembly name, being Common.Logging.Log4Net1211):
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net1211">
<arg key="configType" value="INLINE" />
</factoryAdapter>
</logging>
</common>
https://stackoverflow.com/a/756241/3469201
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>
Then, to determine the file in which you want to save the output you can add the following code in the same .config file:
<configuration>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
...
</configuration>
I'm not familiar with Common.Logging.Log4Net. Here is the simple log4net steps that I use -
Install log4net from NuGet.
Insert the following settings in web.config (you can configure the way you want)
Then log.
If you want to use IoC container, you can read my question I asked last month.
web.config
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG"/>
<appender-ref ref="FileAppender"/>
</root>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="log-file.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
Testing inside Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
XmlConfigurator.Configure();
// You can inject it to your code using IoC container.
var logger = LogManager.GetLogger(typeof(MvcApplication));
logger.Debug("Test Debug.");
logger.Error("Test Error.");
logger.Fatal("Test Fatal.");
logger.Info("Test Info.");
}
}
Result
2015-06-04 11:48:05,885 [1] DEBUG DemoLog4Net.MvcApplication [(null)] - Test Debug.
2015-06-04 11:48:05,921 [1] ERROR DemoLog4Net.MvcApplication [(null)] - Test Error.
2015-06-04 11:48:05,922 [1] FATAL DemoLog4Net.MvcApplication [(null)] - Test Fatal.
2015-06-04 11:48:05,922 [1] INFO DemoLog4Net.MvcApplication [(null)] - Test Info.

Resources