1. Bajar log4net con NuGet
2. Dentro de Properties / AssemblyInfo.cs agregar la siguiente línea:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
3. En web.config, agregar lo siguiente:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="output.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<filter type="log4net.Filter.LoggerMatchFilter">
<loggerToMatch value="Amazon" />
<acceptOnMatch value="false" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
</log4net>
</configuration>
4. Para utilizarlo (por ejemplo en un controller)
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ClientesController));
public ActionResult Index()
{
log.Info("prueba de log!");
return View();
}
Mostrando entradas con la etiqueta log4net. Mostrar todas las entradas
Mostrando entradas con la etiqueta log4net. Mostrar todas las entradas
Como identificar el error cuando log4net no funciona
Agregar dentro de <appSettings> en el web.config, la siguiente linea:
<add key="log4net.Internal.Debug" value="true"/>
Los errores que produce log4net cuando no funciona bien, se despliegan en la ficha Output en Visual Sutdio. En este caso, el problema es que falta el archivo log4net.dll:
log4net:ERROR XmlConfigurator: Failed to parse config file. Is the <configSections> specified as: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for log4net: Could not load file or assembly 'log4net' or one of its dependencies. El sistema no puede encontrar el archivo especificado. (C:\temp\CobranzaGERMAN\Cobranza\Cobranza\web.config line 8) ---> System.IO.FileNotFoundException: Could not load file or assembly 'log4net' or one of its dependencies. El sistema no puede encontrar el archivo especificado.
<add key="log4net.Internal.Debug" value="true"/>
Los errores que produce log4net cuando no funciona bien, se despliegan en la ficha Output en Visual Sutdio. En este caso, el problema es que falta el archivo log4net.dll:
log4net:ERROR XmlConfigurator: Failed to parse config file. Is the <configSections> specified as: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for log4net: Could not load file or assembly 'log4net' or one of its dependencies. El sistema no puede encontrar el archivo especificado. (C:\temp\CobranzaGERMAN\Cobranza\Cobranza\web.config line 8) ---> System.IO.FileNotFoundException: Could not load file or assembly 'log4net' or one of its dependencies. El sistema no puede encontrar el archivo especificado.
Logger log4net en C# (para una aplicacion de escritorio)
Ejemplo de un Rolling log file appender: en este ejemplo, se guarda el log en un archivo de texto, con tamaño máximo de 10Mb (atributo: maximumFileSize).
Cuando se llega al tamaño máximo se sobreescribe el archivo, dejando hasta 5 archivos de backup (atributo: maxSizeRollBackups)
1. Descargar las dll's de log4j desde esta ubicación:
http://apache.mirrors.pair.com//logging/log4net/binaries/log4net-1.2.13-bin-newkey.zip
(http://logging.apache.org/log4net/download_log4net.cgi)
2. Agregar una referencia al archivo log4net.dll
3. En App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:\log\MySampleLogFile.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<filter type="log4net.Filter.LoggerMatchFilter">
<loggerToMatch value="Amazon" />
<acceptOnMatch value="false" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
</log4net>
</configuration>
4. Ejemplo de uso:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
namespace log1
{
class Program
{
private static readonly ILog logger = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
for (int i = 0; i < 100; i++)
{
logger.Debug("Log de debug");
logger.Info("Log informativo");
logger.Warn("Log de warning");
logger.Error("Log de error");
logger.Fatal("Log de error fatal");
}
}
}
}
Cuando se llega al tamaño máximo se sobreescribe el archivo, dejando hasta 5 archivos de backup (atributo: maxSizeRollBackups)
1. Descargar las dll's de log4j desde esta ubicación:
http://apache.mirrors.pair.com//logging/log4net/binaries/log4net-1.2.13-bin-newkey.zip
(http://logging.apache.org/log4net/download_log4net.cgi)
2. Agregar una referencia al archivo log4net.dll
3. En App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:\log\MySampleLogFile.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<filter type="log4net.Filter.LoggerMatchFilter">
<loggerToMatch value="Amazon" />
<acceptOnMatch value="false" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
</log4net>
</configuration>
4. Ejemplo de uso:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
namespace log1
{
class Program
{
private static readonly ILog logger = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
for (int i = 0; i < 100; i++)
{
logger.Debug("Log de debug");
logger.Info("Log informativo");
logger.Warn("Log de warning");
logger.Error("Log de error");
logger.Fatal("Log de error fatal");
}
}
}
}
Suscribirse a:
Entradas (Atom)