你可以在代码中configurationlog4net而不是使用configuration文件?

我明白为什么log4net使用app.config文件来设置日志logging – 所以您可以轻松地更改logging信息的方式,而无需重新编译代码。 但在我的情况下,我不想用我的可执行文件打包一个app.config文件。 我不想修改我的日志logging设置。

有没有办法让我设置日志代码而不是使用app.config

这是我简单的configuration文件:

 <?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文件。 甚至不是作为一个embedded资源,我变成一个stream。 我的目标是完全编程定义logging器。 只是好奇,如果有可能,如果是的话,我可能会find一个语法的例子。

最终解决scheme: 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; } } } 

然后,我所要做的就是用下面的调用replace我调用XML文件的代码:

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

1 (这个答案被OP编辑成问题,我冒昧地把它作为一个社区答案, 在这里看到为什么 )

您也可以完全转义XML,我在这里写了一个最小的编程configuration示例。

简而言之,这里是你所需要的

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

是的,你可以通过调用来configurationlog4net:

 log4net.Config.XmlConfigurator.Configure(XmlElement element) 

请参阅log4net文档 。

或者,您可以创build一个inheritance自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.Filepath后, 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"))