Here is my Nlog.Config code.
<nlog>
<variable name="logFilePath" value="C:\NLog\IDG-${shortdate}.log" />
<targets>
<target name="logfile"
xsi:type="File"
fileName="${logFilePath}"
layout="${longdate} LEVEL=${level:upperCase=true}: ${message}"
keepFileOpen="true" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
<logger name="*" minlevel="Info" writeTo="logfile" />
<logger name="*" minlevel="Warn" writeTo="file"/>
</rules>
</nlog>
and am defining this in my class
private static Logger logger = LogManager.GetCurrentClassLogger();
and then I'm logging the error as:
catch (Exception ex)
{
logger.Error(ex.Message,"test");
}
Can anyone please suggest me if there is any better way to do this, I don't see the file logging in the destined folder.
It seems that you may not be referencing the config section correctly. Try changing your main config file to something like this and remove the Nlog.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<variable name="logFilePath" value="C:\temp\output.log" />
<targets>
<target name="logfile"
xsi:type="File"
fileName="${logFilePath}"
layout="${longdate} LEVEL=${level:upperCase=true}: ${message}"
keepFileOpen="true" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
<logger name="*" minlevel="Info" writeTo="logfile" />
<logger name="*" minlevel="Warn" writeTo="file"/>
</rules>
</nlog>
</configuration>
Related
I have a warning highlighted for the element:
<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability Name="runFullTrust" />
<rescap:Capability Name="localSystemServices" />
<rescap:Capability Name="packagedServices" />
</Capabilities>
With the below detail:
The element 'Capabilities' in namespace 'http://schemas.microsoft.com/appx/manifest/foundation/windows10' has invalid
child element 'Capability' in namespace
'http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities'. List of possible elements
expected: 'CapabilityChoice' in namespace 'http://schemas.microsoft.com/appx/manifest/foundation/windows10' as well as
'Capability' in namespace 'http://schemas.microsoft.com/appx/manifest/uap/windows10' as well as 'Capability' in
namespace 'http://schemas.microsoft.com/appx/manifest/foundation/windows10' as well as 'Capability' in namespace
'http://schemas.microsoft.com/appx/manifest/uap/windows10/4' as well as 'Capability' in namespace
'http://schemas.microsoft.com/appx/manifest/uap/windows10/6' as well as 'Capability' in namespace
'http://schemas.microsoft.com/appx/manifest/uap/windows10/7' as well as 'Capability' in namespace
'http://schemas.microsoft.com/appx/manifest/uap/windows10/3' as well as 'Capability' in namespace
'http://schemas.microsoft.com/appx/manifest/uap/windows10/2' as well as 'CustomCapabilityChoice' in namespace
'http://schemas.microsoft.com/appx/manifest/foundation/windows10' as well as 'CustomCapability' in namespace
'http://schemas.microsoft.com/appx/manifest/uap/windows10/4' as well as 'Dev....
The Package.appmanifest xml manifest is below:
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
xmlns:desktop2="http://schemas.microsoft.com/appx/manifest/desktop/windows10/2"
xmlns:desktop6="http://schemas.microsoft.com/appx/manifest/desktop/windows10/6"
IgnorableNamespaces="uap rescap">
<Identity
Name="11d14331-0000-0000-0000-3c2e4cc6d69d"
Publisher="CN=my.name"
Version="1.0.10.0" />
<Properties>
<DisplayName>My Agent</DisplayName>
<PublisherDisplayName>My</PublisherDisplayName>
<Logo>Images\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.14393.0" MaxVersionTested="10.0.14393.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate"/>
</Resources>
<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe" EntryPoint="$targetentrypoint$">
<uap:VisualElements
DisplayName="My Agent"
Description="My Agent."
BackgroundColor="transparent"
Square150x150Logo="Images\Square150x150Logo.png"
Square44x44Logo="Images\Square44x44Logo.png">
<uap:DefaultTile Wide310x150Logo="Images\Wide310x150Logo.png" />
<uap:SplashScreen Image="Images\SplashScreen.png" />
</uap:VisualElements>
<Extensions>
<desktop6:Extension Category="windows.service" EntryPoint="Windows.FullTrustApplication" Executable="Agent\Agent.exe">
<desktop6:Service Name="Agent" StartAccount="localSystem" StartupType="auto"/>
</desktop6:Extension>
</Extensions>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability Name="runFullTrust" />
<rescap:Capability Name="localSystemServices" />
<rescap:Capability Name="packagedServices" />
</Capabilities>
<Extensions>
<desktop2:Extension Category="windows.firewallRules">
<desktop2:FirewallRules Executable="Agent\Agent.exe">
<desktop2:Rule Direction="in" IPProtocol="TCP" Profile="all"/>
<desktop2:Rule Direction="in" IPProtocol="UDP"
Profile="all"/>
<desktop2:Rule Direction="out"
IPProtocol="TCP"
Profile="all"/>
<desktop2:Rule Direction="out"
IPProtocol="UDP"
Profile="all"/>
</desktop2:FirewallRules>
</desktop2:Extension>
</Extensions>
</Package>
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" />
I need to print each level logs in a seperate file. For example, Debug msg alone should print in debug file and not other level logs should print in debug file..
I am new to logs , so can you correct the code.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
<Properties>
<Property name="debug">D://logs/debug.log</Property>
<Property name="info">D://logs/info.log</Property>
<Property name="warn">D://logs/warn.log</Property>
<Property name="error">D://logs/error.log</Property>
<Property name="fatal">D://logs/fatal.log</Property>
</Properties>
<Appenders>
<Appender type="File" name="Debug_file" fileName="${debug}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
<Appender type="File" name="Info_file" fileName="${info}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
<Appender type="File" name="Warn_file" fileName="${warn}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
<Appender type="File" name="Error_file" fileName="${error}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
<Appender type="File" name="Fatal_file" fileName="${fatal}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>
There are at least 2 different ways you could achieve what you want. One way is to use the LevelRangeFilter (see log4j2 javadoc) as shown in the following example configuration:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="LOG_PATTERN">%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
</Properties>
<Appenders>
<File name="TraceFile" fileName="logs/Trace.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
<LevelRangeFilter minLevel="TRACE" maxLevel="TRACE" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
<File name="DebugFile" fileName="logs/Debug.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
<LevelRangeFilter minLevel="DEBUG" maxLevel="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
<File name="InfoFile" fileName="logs/Info.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
<LevelRangeFilter minLevel="INFO" maxLevel="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
<File name="WarnFile" fileName="logs/Warn.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
<LevelRangeFilter minLevel="WARN" maxLevel="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
<File name="ErrorFile" fileName="logs/Error.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
<LevelRangeFilter minLevel="ERROR" maxLevel="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
<File name="FatalFile" fileName="logs/Fatal.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
<LevelRangeFilter minLevel="FATAL" maxLevel="FATAL" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
</Appenders>
<Loggers>
<Root level="TRACE">
<AppenderRef ref="TraceFile" />
<AppenderRef ref="DebugFile" />
<AppenderRef ref="InfoFile" />
<AppenderRef ref="WarnFile" />
<AppenderRef ref="ErrorFile" />
<AppenderRef ref="FatalFile" />
</Root>
</Loggers>
</Configuration>
The above configuration ensures that each appender accepts log events of exactly one level only.
Another option is to use the RoutingAppender (see log4j2 manual) as demonstrated in the following configuration:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="LOG_PATTERN">%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
</Properties>
<Appenders>
<File name="TraceFile" fileName="logs/Trace.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
</File>
<File name="DebugFile" fileName="logs/Debug.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
</File>
<File name="InfoFile" fileName="logs/Info.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
</File>
<File name="WarnFile" fileName="logs/Warn.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
</File>
<File name="ErrorFile" fileName="logs/Error.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
</File>
<File name="FatalFile" fileName="logs/Fatal.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
</File>
<Routing name="Routing">
<Routes>
<Script name="RoutingInit" language="JavaScript"><![CDATA[
logEvent.getLevel();]]>
</Script>
<Route ref="TraceFile" key="TRACE" />
<Route ref="DebugFile" key="DEBUG" />
<Route ref="InfoFile" key="INFO" />
<Route ref="WarnFile" key="WARN" />
<Route ref="ErrorFile" key="ERROR" />
<Route ref="FatalFile" key="FATAL" />
</Routes>
</Routing>
</Appenders>
<Loggers>
<Root level="TRACE">
<AppenderRef ref="Routing" />
</Root>
</Loggers>
</Configuration>
In this configuration the appenders are indifferent toward the level of the log event. The RoutingAppender is the decision maker with regard to which events go to which appender. I tend to prefer using RoutingAppender because it can be made more compact by taking advantage of the log4j2 plugin system. If you add your own lookup which returns the name of the level associated with the log event you can use that lookup to dynamically create appenders on the fly. The code for the lookup and the revised configuration are shown below:
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;
#Plugin(name = "level", category = "Lookup")
public class LevelLookup implements StrLookup{
/**
* Lookup the value for the key.
* #param key the key to be looked up, may be null
* #return The value for the key.
*/
public String lookup(String key) {
return null;
}
/**
* Lookup the value for the key using the data in the LogEvent.
* #param event The current LogEvent.
* #param key the key to be looked up, may be null
* #return The value associated with the key.
*/
public String lookup(LogEvent event, String key) {
return event.getLevel().name();
}
}
Here is the revised configuration that takes advantage of the new lookup:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="LOG_PATTERN">%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
</Properties>
<Appenders>
<Routing name="Routing">
<Routes pattern="$${level:}">
<Route>
<File name="${level:}File" fileName="logs/${level:}.log" immediateFlush="true"
append="true">
<PatternLayout pattern="${LOG_PATTERN}" />
</File>
</Route>
</Routes>
</Routing>
</Appenders>
<Loggers>
<Root level="TRACE">
<AppenderRef ref="Routing" />
</Root>
</Loggers>
</Configuration>
As with the other configurations this will send log messages to a file based on the log level of the log event. For example INFO level events will be logged to logs/INFO.log
I hope this helps you.
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net" />
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.serviceModel>
<!-- Redacted -->
</system.serviceModel>
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="logs\" />
<datePattern value="'Proxy_'dd.MM.yyyy'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<priority value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<category name="Client.log">
<priority value="ALL" />
</category>
</log4net>
<applicationSettings>
<!-- Redacted -->
</applicationSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
I have the above config for my windows service when it's installed, and I'm initializing my logger like so in the Progam.cs file on the service that I'm installing:
static void Main()
{
XmlConfigurator.Configure();
_logger.Debug("ProxyServerService Started.");
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ProxyServerService()
};
ServiceBase.Run(ServicesToRun);
_logger.Debug("ProxyServerService Terminated.");
}
When I use pretty much the same configuration in an application that communicates with this service it creates a log directory and writes logs to that directory. But when I run the service nothing happens.
Turns out that the reason I couldn't see the logs is because I'd configured the logger the log in the active directory, which is Windows\system32 and windows wouldn't let me do that.
I changed the following line:
<file value="logs\" />
To:
<file value="C:\AppName\logs\" />
And it works fine.
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.