可以用代码配置 log4net 而不使用配置文件吗?

我理解 log4net 为什么使用 app.config文件来设置日志记录-这样你就可以轻松地改变信息的记录方式,而不需要重新编译你的代码。但是在我的例子中,我不想用可执行文件打包 app.config文件。我也不想修改我的日志设置。

有没有一种方法可以让我在代码中设置日志,而不是使用 app.config

下面是我的简单配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs\EventLog.txt" />
<appendToFile value="false" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="1GB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="MemoryAppender" type="log4net.Appender.MemoryAppender">
</appender>
<root>
<level value="Info" />
<appender-ref ref="RollingLogFileAppender" />
<appender-ref ref="MemoryAppender" />
</root>
</log4net>
</configuration>

编辑:

要完全清楚: 我的目标是没有 XML 文件。即使是作为一个嵌入式资源,我把它变成一个流。我的目标是完全以编程方式定义日志记录器。只是好奇这是否可能,如果可能的话,我在哪里可以找到一个语法的例子。

99449 次浏览

是的,您可以通过调用:

log4net.Config.XmlConfigurator.Configure(XmlElement element)

参见 Log4net 文档

您还可以完全转义 XML,我编写了一个使用最小编程配置 给你的示例。

简而言之,这就是你需要的

var tracer = new TraceAppender();
var hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.AddAppender(tracer);
var patternLayout = new PatternLayout {ConversionPattern = "%m%n"};
patternLayout.ActivateOptions();
tracer.Layout = patternLayout;
hierarchy.Configured = true;

最终解决方案: < sub > 1

对于任何将来可能偶然发现这一点的人,以下是我所做的。我创建了以下静态类:

using log4net;
using log4net.Repository.Hierarchy;
using log4net.Core;
using log4net.Appender;
using log4net.Layout;


namespace Spectrum.Logging
{
public class Logger
{
public static void Setup()
{
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();


PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
patternLayout.ActivateOptions();


RollingFileAppender roller = new RollingFileAppender();
roller.AppendToFile = false;
roller.File = @"Logs\EventLog.txt";
roller.Layout = patternLayout;
roller.MaxSizeRollBackups = 5;
roller.MaximumFileSize = "1GB";
roller.RollingStyle = RollingFileAppender.RollingMode.Size;
roller.StaticLogFileName = true;
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);


MemoryAppender memory = new MemoryAppender();
memory.ActivateOptions();
hierarchy.Root.AddAppender(memory);


hierarchy.Root.Level = Level.Info;
hierarchy.Configured = true;
}
}
}

然后,我所要做的就是将调用 XML 文件的代码替换为以下调用:

//XmlConfigurator.Configure(new FileInfo("app.config")); // Not needed anymore
Logger.Setup();

1(这个答案已经被 OP 编辑成了问题,我自作主张把它变成了一个社区答案,看看这里为什么)

或者,您可以创建一个从 log4net.Config.ConfiguratorAttribute 继承的自定义属性,并在那里进行硬编码配置:

using log4net.Appender;
using log4net.Config;
using log4net.Core;
using log4net.Layout;
using log4net.Repository;
using log4net.Repository.Hierarchy;
using System;
using System.Reflection;


namespace ConsoleApplication1
{
[AttributeUsage(AttributeTargets.Assembly)]
public class MyConfiguratorAttribute : ConfiguratorAttribute
{
public MyConfiguratorAttribute()
: base(0)
{
}


public override void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository)
{
var hierarchy = (Hierarchy)targetRepository;
var patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
patternLayout.ActivateOptions();


var roller = new RollingFileAppender();
roller.AppendToFile = false;
roller.File = @"Logs\EventLog.txt";
roller.Layout = patternLayout;
roller.MaxSizeRollBackups = 5;
roller.MaximumFileSize = "1GB";
roller.RollingStyle = RollingFileAppender.RollingMode.Size;
roller.StaticLogFileName = true;
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);


hierarchy.Root.Level = Level.Info;
hierarchy.Configured = true;
}
}
}

然后将以下内容添加到.cs 文件中:

[assembly: ConsoleApplication1.MyConfigurator]

在我发现了两个警告之后,这个被接受的答案奏效了:

  • 起初它对我不起作用,但是在对 roller.File属性使用完全绝对路径之后,它开始工作了。
  • 我必须在 F # 中使用它(在 fsx 脚本中) ,所以在从 C # 转换它时遇到了一些问题。如果你对最终结果感兴趣(包括下载 log4net nuget 软件包的方法) ,请看下面:

Nuget _ log4net. fsx:

#!/usr/bin/env fsharpi


open System
open System.IO
open System.Net


#r "System.IO.Compression.FileSystem"
open System.IO.Compression


type DummyTypeForLog4Net () =
do ()


module NetTools =


let DownloadNuget (packageId: string, packageVersion: string) =
use webClient = new WebClient()
let fileName = sprintf "%s.%s.nupkg" packageId packageVersion


let pathToUncompressTo = Path.Combine("packages", packageId)
if (Directory.Exists(pathToUncompressTo)) then
Directory.Delete(pathToUncompressTo, true)
Directory.CreateDirectory(pathToUncompressTo) |> ignore
let fileToDownload = Path.Combine(pathToUncompressTo, fileName)


let nugetDownloadUri = Uri (sprintf "https://www.nuget.org/api/v2/package/%s/%s" packageId packageVersion)
webClient.DownloadFile (nugetDownloadUri, fileToDownload)


ZipFile.ExtractToDirectory(fileToDownload, pathToUncompressTo)


let packageId = "log4net"
let packageVersion = "2.0.5"
NetTools.DownloadNuget(packageId, packageVersion)


let currentDirectory = Directory.GetCurrentDirectory()


// https://stackoverflow.com/a/19538654/6503091
#r "packages/log4net/lib/net45-full/log4net"


open log4net
open log4net.Repository.Hierarchy
open log4net.Core
open log4net.Appender
open log4net.Layout
open log4net.Config


let patternLayout = PatternLayout()
patternLayout.ConversionPattern <- "%date [%thread] %-5level %logger - %message%newline";
patternLayout.ActivateOptions()


let roller = RollingFileAppender()
roller.AppendToFile <- true
roller.File <- Path.Combine(currentDirectory, "someLog.txt")
roller.Layout <- patternLayout
roller.MaxSizeRollBackups <- 5
roller.MaximumFileSize <- "1GB"
roller.RollingStyle <- RollingFileAppender.RollingMode.Size
roller.StaticLogFileName <- true
roller.ActivateOptions ()


let hierarchy = box (LogManager.GetRepository()) :?> Hierarchy
hierarchy.Root.AddAppender (roller)


hierarchy.Root.Level <- Level.Info
hierarchy.Configured <- true
BasicConfigurator.Configure(hierarchy)


let aType = typedefof<DummyTypeForLog4Net>
let logger = LogManager.GetLogger(aType)


logger.Error(new Exception("exception test"))

对于那些不想将 appender 添加到 Root 日志记录器,而是添加到当前/其他日志记录器的用户:

//somewhere you've made a logger
var logger = LogManager.GetLogger("MyLogger");


// now add appender to it
var appender = BuildMyAppender();
((log4net.Repository.Hierarchy.Logger)logger).AddAppender(appender);


logger.Debug("MyLogger with MyAppender must work now");


// and remove it later if this code executed multiple times (loggers are cached, so you'll get logger with your appender attached next time "MyLogger")
((log4net.Repository.Hierarchy.Logger)logger).RemoveAppender(sbAppender);

虽然公认的答案在大多数情况下有效,但它有一些缺点。

  • 它只能保存最后5根日志。
  • 日志大小被设置为1GB,这对于大多数记事本应用程序来说太大而无法打开。
  • 因为它锁定了日志文件,所以它不适合多线程应用程序,比如 Web 应用程序。
  • 由于 date 是以文件名作为前缀的,所以在窗口中使用它不方便
  • 每次应用程序重新启动时,它都会覆盖日志,如果您计划保留日志,这也是不合适的。
  • 正如注释中提到的,它需要进行一些修改,以便在某些情况下能够正确工作。

因此,更广泛的一点配置。我创建了一个类,它使日志记录变得更容易一些。显然,如果您愿意,您可以选择配置部分。

using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using log4net.Layout;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Web;


public enum LogType { Info, Debug, Warn, Error, Fatal };


public class Logger {


private const string LOG_NAMESPACE = "APP_NAME";
private const string LOG_FILENAME_PREFIX = @"D:\Logs\";
private static readonly Level LOG_LEVEL = Level.Debug;
private static readonly ILog log = LogManager.GetLogger(LOG_NAMESPACE);


#region static Logger()
// Static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced
static Logger() {
Hierarchy hierarchy = (Hierarchy) LogManager.GetRepository();
hierarchy.Root.RemoveAllAppenders();                            // Clear all previously added repositories.
hierarchy.Root.Level = LOG_LEVEL;                               // Set Log level
PatternLayout layout = new PatternLayout() { ConversionPattern = "%d{yyyy-MM-dd HH:mm:ss.fff} %4t %-5p %m%n" }; // Log line format: Include millisecond precision, thread ID, Log type,
layout.ActivateOptions();                                       // Apply Configuration


RollingFileAppender RFA = new RollingFileAppender();
RFA.Name = LOG_NAMESPACE;                                       // Set name of appender
RFA.File = LOG_FILENAME_PREFIX + LOG_NAMESPACE;                 // Set file name prefix
RFA.LockingModel = new FileAppender.MinimalLock();              // Minimum lock time required, makes file available for reading
RFA.AppendToFile = true;                                        // Do not overwrite existing logs, append to them.
RFA.DatePattern = ".yyyy.MM.dd'.log'";                          // Add file extension here, to preserve the file extension
RFA.Encoding = Encoding.UTF8;                                   // Set format of file to UTF8 for international characters.
RFA.CountDirection = 1;                                         // Increment file name in bigger number is newest, instead of default backward.
RFA.MaximumFileSize = "100MB";                                  // Maximum size of file that I could open with common notepad applications
RFA.RollingStyle = RollingFileAppender.RollingMode.Composite;   // Increment file names by both size and date.
RFA.StaticLogFileName = false;
RFA.MaxSizeRollBackups = -1;                                    // Keep all log files, do not automatically delete any
RFA.PreserveLogFileNameExtension = true;                        // This plus extension added to DatePattern, causes to rolling size also work correctly


RFA.Layout = layout;
RFA.ActivateOptions();                                          // Apply Configuration


hierarchy.Root.AddAppender(RFA);
BasicConfigurator.Configure(hierarchy);                         // Apply Configuration
}
#endregion


#region public static int Log(...)
public static void Log(string Description, LogType logtype = LogType.Info) {
switch (logtype) {
case LogType.Debug:
log.Debug(Description);
break;
case LogType.Info:
log.Info(Description);
break;
case LogType.Warn:
log.Warn(Description);
break;
case LogType.Error:
log.Error(Description);
break;
case LogType.Fatal:
log.Fatal(Description);
break;
}
}
#endregion


#region public static int Log(...)
public static void Log(string Message, Exception ex) {
log.Fatal(Message, ex);
}
#endregion


}




然后对消息和异常进行日志记录,如下所示

Logger.Log("I was here", LogType.Debug);
Logger.Log("I am info message");
Logger.Log("An error", LogType.Error);
Logger.Log("An Exception", ex); // ex is of type Exception

由于 log4net 将滚动数据添加到文件名(在文件扩展名后添加)的怪异方式,文件松散的文件资源管理器关联。修复 .log被添加到 DatePattern 的问题。它还将在扩展之前正确地添加文件增量(可能是因为 bug)在版本 1.2.11.0上测试

备注:

  • 不需要外部调用进行初始化,这将在应用程序启动时(或调用 Logger 时)进行初始化。第一次记录
  • 您可以将所有的类常量移动到您自己的配置文件中,使这个类更加通用和可重用。
  • 注意,没有指定名称空间,这将使 Logger 类在所有名称空间中都可用。
  • Log4net 提供了5种记录消息的方法,这有点不便于记忆。因此,Logger.Log方法默认使用 info
  • 一个不相关的说明: 如果你的应用程序运行在服务器或网络上,保持你的日志文件远离操作系统驱动器和应用程序文件夹。