每天创建一个新的日志文件

Jas*_* T. 14 c# asp.net logging log4net winforms

标题暗示如何在C#中每天创建一个新的日志文件?现在,该程序可能不一定全天候运行,但只能在工作时间调用.所以我需要做两件事.

  1. 我怎样才能每天创建一个新的日志文件?日志文件的名称将采用MMDDYYYY.txt格式
  2. 我怎样才能在午夜之后创建它,以防它在夜间的所有时间都运行?

Dan*_*son 39

更新2018:我现在更喜欢使用NLog

以前关于log4net的答案:

此示例显示如何配置RollingFileAppender以在日期期间滚动日志文件.此示例将每分钟滚动日志文件!要更改滚动周期,请调整DatePattern值.例如,日期模式"yyyyMMdd"将每天滚动.
有关可用模式的列表,请参见System.Globalization.DateTimeFormatInfo.

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="C:\temp\rolling.log" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value="yyyyMMdd-HHmm" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
</appender>
Run Code Online (Sandbox Code Playgroud)

  • 是的你可以使用大小和日期一起使用rollingstyle Composite.在这里看到:http://logging.apache.org/log4net/release/config-examples.html#rollingfileappender在Rolling File Appender标题下的第3个框 (2认同)

Abe*_*ler 8

我推荐这样的东西:

string logFile = DateTime.Now.ToString("yyyyMMdd") + ".txt";
if (!System.IO.File.Exists(logFile))
{
    System.IO.File.Create(logFile);   
}
//append to logFile here...
Run Code Online (Sandbox Code Playgroud)

你有什么理由想在午夜之后创造它吗?如果您在记录错误时不存在,为什么不创建它呢?

还注意到我改变了日期格式.这将允许您按名称对文件进行排序并按顺序获取它们.在以任何方式弄乱日期时,我总是使用这种格式.


Ran*_*pho 8

其他人提到了Log4Net,所以我会继续使用企业库记录块,这也很有能力做你想做的事情.

你能否列举一些代码,说明每天进行这种滚动是多么容易?它比log4Net示例更容易吗? - 丹尼尔戴森

当然.通常,可以使用Enterprise Library Configuration Tool来构建配置; 这个工具需要一点点习惯,但一旦你理解它是如何工作的,它就非常强大.也就是说,您也可以app.config手动编辑.

这是我提到的工具的输出,它几乎将所有内容转储到每天滚动的滚动平面文件中(或者如果它超过2MB).格式是工具提供的默认值.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <loggingConfiguration name="" tracingEnabled="true" defaultCategory="Category">
        <listeners>
            <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                formatter="Text Formatter" rollInterval="Day" rollSizeKB="2000" />
        </listeners>
        <formatters>
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
                name="Text Formatter" />
        </formatters>
        <categorySources>
            <add switchValue="All" name="Category">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </add>
        </categorySources>
        <specialSources>
            <allEvents switchValue="All" name="All Events">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </allEvents>
            <notProcessed switchValue="All" name="Unprocessed Category">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </notProcessed>
            <errors switchValue="All" name="Logging Errors &amp; Warnings">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </errors>
        </specialSources>
    </loggingConfiguration>
</configuration>
Run Code Online (Sandbox Code Playgroud)


kwc*_*cto 6

试试NLog(nlog-project.org).在我看来,它比Log4Net更灵活,更易于使用.

示例NLog.config:

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}" 
            fileName="${basedir}/${shortdate}/${windows-identity:domain=false}.${level}.log" />
    </targets>

    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>
Run Code Online (Sandbox Code Playgroud)

有关更多示例(包括除File之外的其他日志记录目标),请参阅Github上的NLog配置示例

  • 你根本没有回答这个问题.如何在NLog中执行此操作的示例...? (3认同)

gle*_*ron 3

您不需要在特定时间创建它 - 在最简单的情况下,您只需在启动应用程序的日志记录服务时检查是否存在以今天日期为名称的日志文件,如果没有,您可以创建在开始附加之前先添加一个。

对于此设置,您需要特别注意的唯一情况是应用程序在午夜之后运行。