C# 您可以在代码中配置 log4net 而不是使用配置文件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16336917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you configure log4net in code instead of using a config file?
提问by Michael Mankus
I understand why log4net uses app.configfiles for setting up logging - so you can easily change how information is logged without needing to recompile your code. But in my case I do not want to pack a app.configfile with my executable. And I have no desire to modify my logging setup.
我理解为什么 log4net 使用app.config文件来设置日志记录 - 这样您就可以轻松更改信息的记录方式,而无需重新编译您的代码。但就我而言,我不想app.config用我的可执行文件打包文件。而且我不想修改我的日志记录设置。
Is there a way for me to set up logging in code rather than using the app.config?
有没有办法让我设置登录代码而不是使用app.config?
Here is my simple config file:
这是我的简单配置文件:
<?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>
EDIT:
编辑:
To be completely clear: It is my goal to have no XML file. Not even as an embedded resource that I turn into a stream. My goal was to define the logger completely programmatically. Just curious if it's possible and if so where I might find an example of the syntax.
完全清楚:我的目标是没有 XML 文件。甚至不是作为我变成流的嵌入式资源。我的目标是完全以编程方式定义记录器。只是好奇是否可能,如果可能,我可以在哪里找到语法示例。
采纳答案by Philipp M
FINAL SOLUTION:1
最终解决方案:1
For anyone who may stumble upon this in the future, here is what I did. I made the static class below:
对于将来可能偶然发现此问题的任何人,这就是我所做的。我做了下面的静态类:
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;
}
}
}
And then all I had to do was replace the code where I called the XML file with the following call:
然后我所要做的就是用以下调用替换我调用 XML 文件的代码:
//XmlConfigurator.Configure(new FileInfo("app.config")); // Not needed anymore
Logger.Setup();
1(this answer was edited into the question by the OP, I took the liberty to make it a community answer, see here why)
1 (此答案已被 OP 编辑为问题,我冒昧地将其作为社区答案,请在此处查看原因)
回答by Joe
Yes, you can configure log4net by calling:
是的,您可以通过调用来配置 log4net:
log4net.Config.XmlConfigurator.Configure(XmlElement element)
See the log4net documentation.
请参阅log4net 文档。
回答by oleksii
You can also escape XML completely, I wrote a sample with minimal programmatic configuration here.
您也可以完全转义 XML,我在这里编写了一个具有最少编程配置的示例。
In a nutshell, here is what you need
简而言之,这就是你需要的
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;
回答by Jas
Alternatively you could create a custom attribute that inherits from log4net.Config.ConfiguratorAttribute and hard-code you configuration there:
或者,您可以创建一个从 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;
}
}
}
Then add the following to a .cs file:
然后将以下内容添加到 .cs 文件中:
[assembly: ConsoleApplication1.MyConfigurator]
回答by ympostor
The accepted answer works after I found two caveats:
在我发现两个警告后,接受的答案有效:
- It was not working for me at first, but after using a full absolue path for the
roller.Fileproperty, it started work. - I had to use this in F# (in a fsx script), so had some issues when converting it from C#. If you're interested in the end result (including a way to download log4net nuget package), see below:
- 起初它对我不起作用,但在为该
roller.File属性使用完整的绝对路径后,它开始工作。 - 我不得不在 F# 中使用它(在 fsx 脚本中),所以在从 C# 转换它时遇到了一些问题。如果您对最终结果感兴趣(包括下载 log4net nuget 包的方法),请参见下文:
nuget_log4net.fsx:
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"))
回答by Vladislav Kostenko
For those who don't want to add appender to Root logger, but to current/other logger:
对于那些不想将 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);

