c#使用log4net
When you write computer code in C#, it's a good idea to include logging code. That way, when something goes wrong, you know where to start looking. The Java world has been doing this for years. You can use log4net for this purpose. It is part of Apache log4j 2, a popular open-source logging framework.
用C#编写计算机代码时,最好包含日志记录代码。 这样,当出现问题时,您就知道从哪里开始寻找。 Java世界已经这样做了多年。 您可以将log4net用于此目的。 它是Apache log4j 2(流行的开源日志记录框架)的一部分。
This isn't the only .NET logging framework; there are many. However, the Apache name is trusted and the original Java logging framework has been around for more than 15 years.
这不是唯一的.NET日志记录框架。 有许多。 但是, Apache名称是受信任的,并且原始的Java日志记录框架已经存在了15年以上。
为什么使用Log4net日志记录框架? ( Why Use a Log4net Logging Framework? )
When an application or server crashes, you are left wondering why. Was it a hardware failure, malware, maybe a Denial of Service attack, or some odd combination of keys that manages to bypass all your code checks? You just don't know.
当应用程序或服务器崩溃时,您不知道为什么。 是硬件故障,恶意软件,也许是拒绝服务攻击,还是设法绕过所有代码检查的某些奇怪组合键? 你就是不知道
You need to find out why a crash occurred so it can be corrected. With logging enabled, you might be able to see why it happened.
您需要找出发生崩溃的原因,以便可以进行纠正。 启用日志记录后,您也许可以看到它发生的原因。
入门 ( Getting Started )
Download the log4net file from the Apache log4net website. Verify the integrity of the downloaded files using the PGP signature or MD5 checksums. The checksums are not as strong indicators as the PGP signature.
从Apache log4net网站下载log4net文件。 使用PGP签名或MD5校验和验证下载文件的完整性。 校验和不像PGP签名那样有力。
使用Log4net ( Using Log4net )
Log4net supports seven levels of logging from none to all in increasing priority. These are:
Log4net支持七个级别的日志记录,从无到有都以更高的优先级进行记录。 这些是:
- OFF 关
- FATAL 致命
- ERROR 错误
- WARN 警告
- INFO 信息
- DEBUG 调试
- ALL 所有
The higher levels include all the lower ones. When debugging, using DEBUG shows all, but on production, you might only be interested in FATAL. This choice can be made at the component level programmatically or in an XML Config file.
较高的级别包括所有较低的级别。 调试时,使用DEBUG可以显示所有内容,但在生产中,您可能只对FATAL感兴趣。 可以在组件级别以编程方式或在XML Config文件中进行选择。
记录器和附加器 ( Loggers and Appenders )
For flexibility, log4net uses loggers, appenders, and layouts. A logger is an object that controls logging and is an implementation of the ILog interface, which specifies five boolean methods: isDebugEnabled, IsInfoEnabled, IsWarnEnabled, IsErrorEnabled and IsFatalEnabled. It also specifies the five methods—Debug, Info, Warn, Error andFatal—along with overloads and five formatted string versions. You can see the full ILog interface in the log4net online manual.
为了提高灵活性,log4net使用记录器,附加器和布局。 记录器是控制日志记录的对象,并且是ILog接口的实现,该接口指定五个布尔方法:isDebugEnabled,IsInfoEnabled,IsWarnEnabled,IsErrorEnabled和IsFatalEnabled。 它还指定了五个方法(调试,信息,警告,错误和致命)以及重载和五个格式化的字符串版本。 您可以在log4net在线手册中看到完整的ILog界面。
Loggers are assigned one of the levels but not ALL or OFF, only the other five.
记录器被分配了一个级别,但没有分配ALL或OFF,仅分配了其他五个级别。
Appenders control where the logging goes. It can be into a database, to an in-memory buffer, to the console, to a remote host, to a text file with rolling logs, the Windows Event Log, or even to email via SMTP. There are 22 appenders in all, and they can be combined so you have plenty of choices. Appenders are appended (hence the name) to a logger.
Appender控制着日志的去向。 它可以进入数据库,内存缓冲区,控制台,远程主机,带有滚动日志的文本文件,Windows事件日志,甚至通过SMTP发送电子邮件。 共有22个附加程序,可以将它们组合在一起,因此您有很多选择。 Appender会附加到记录器中(因此而得名)。
Appenders filter events by matching substrings, event level, range of levels and start of the logger name.
Appender通过匹配子字符串,事件级别,级别范围和记录器名称的开头来过滤事件。
版面 ( Layouts )
Finally, there are seven layouts that can be associated with an Appender. These control how the event's message is logged and can include exception text, timestamp layouts, and XML elements.
最后,有七个可与Appender关联的布局。 这些控件控制事件消息的记录方式,并且可以包括异常文本,时间戳记布局和XML元素 。
使用XML进行配置 ( Configuring With XML )
Although configuring can be done programmatically, it can also be done with XML Config files. Why would you prefer config files over code changes? Simple, it's far easier to have a support guy make a change to a config file than have to get a programmer to change code, test and redeploy a new version. So config files are the way to go. The simplest possible path is to add App.config your project, as shown in the example below:
尽管可以通过编程方式完成配置,但是也可以使用XML Config文件来完成配置。 为什么您更喜欢配置文件而不是代码更改? 简单来说,让支持人员对配置文件进行更改要比让程序员更改代码,测试和重新部署新版本容易得多。 因此,配置文件是必经之路。 最简单的方法是将App.config添加到项目中,如以下示例所示:
<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections> <log4net> <root> <level value="DEBUG"/> <appender-ref ref="LogFileAppender" /> </root> <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" > <file value=" log.txt"/> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="5" /> <maximumFileSize value="10MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d [%t] %-5p %c %m%n" /> </layout> </appender> </log4net></configuration>
<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections> <log4net> <root> <level value="DEBUG"/> <appender-ref ref="LogFileAppender" /> </root> <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" > <file value=" log.txt"/> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="5" /> <maximumFileSize value="10MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d [%t] %-5p %c %m%n" /> </layout> </appender> </log4net></configuration>
The log4net online documentation explains all the config file fields. Having set up App.config, add using log4net and this line:
log4net在线文档介绍了所有配置文件字段。 设置App.config后,使用log4net和以下行添加:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Plus the actual logger has to be fetched with a call to LogManager.GetLogger(...). The GetLogger is usually called with the typeof(class) that it's used in, but this function call also fetches that:
另外,必须通过调用LogManager.GetLogger(...)来获取实际的记录器。 通常使用其使用的typeof(class)来调用GetLogger,但是此函数调用还可以获取以下内容:
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType
This example shows both in with one commented, so you can choose.
本示例在两个示例中都显示了一个注释,因此可以选择。
using log4net;[assembly: log4net.Config.XmlConfigurator(Watch = true)]namespace gvmake{ class Program { private static readonly ILog log = LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) ; //private static readonly ILog log = LogManager.GetLogger(typeof (Program)) ; static void Main(string[] args) { log.Debug("Application Starting") ; } }}
using log4net;[assembly: log4net.Config.XmlConfigurator(Watch = true)]namespace gvmake{ class Program { private static readonly ILog log = LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) ; //private static readonly ILog log = LogManager.GetLogger(typeof (Program)) ; static void Main(string[] args) { log.Debug("Application Starting") ; } }}
翻译自: https://www.thoughtco.com/logging-in-c-with-log4net-958371
c#使用log4net