[英]Appending to File using log4net in C#
我是log4net的新手,並且想創建一個執行以下操作的簡單控制台應用程序:
讀取數字作為輸入
循環許多迭代
MM/DD/YYYY
輸入: <num>
-時間: <time>
ms
在我的AssemblyInfo.cs中,添加了以下行:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
我的App.config看起來像這樣:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="MyLog.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%dateExtra Info: %property{input}%property{time}%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
我的代碼如下所示:
using log4net;
using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
private static long num;
private static readonly ILog log = LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
Console.Write("Please enter a number: ");
try
{
// gets number as input
num = long.Parse(Console.ReadLine());
if (num <= 0) throw new Exception("Number must be positive and non zero");
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
Console.Read();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.Read();
}
// create new stopwatch instance
Stopwatch sw = new Stopwatch();
// starts the timer
sw.Start();
// runs loop [num] times
for (long i = 0; i < num; i++) ;
// stops the timer
sw.Stop();
Console.WriteLine("Loop ran for {0}ms", sw.ElapsedMilliseconds);
GlobalContext.Properties["input"] = " - Input : " + num;
GlobalContext.Properties["time"] = " - Time : " + sw.ElapsedMilliseconds + "ms";
Console.Read();
}
}
}
該文件確實創建了,但是創建為空。 這可能是什么問題?
您需要使用以下命令記錄一些內容
log.Info(string.Format("Input: {0} - Time: {1}ms", input, time));
那就像
using log4net;
using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
private static long num;
private static readonly ILog log = LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
...
Console.WriteLine("Loop ran for {0}ms", sw.ElapsedMilliseconds);
log.Info(string.Format("Input: {0} - Time: {1}ms", num, sw.ElapsedMilliseconds));
...
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.