如何在页眉/页脚中使用日期模式? [英] How do I use a date pattern in a header/footer?

查看:74
本文介绍了如何在页眉/页脚中使用日期模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我app.config中的附加程序配置.这只是打印出文字字符串,而不是将其转换为日期(即,它实际上打印"[START:%date {MM/dd/yy HH:mm}]").

Here's my appender configuration from my app.config. This just prints out the literal string instead of translating it to the date (i.e., it literally prints "[START: %date{MM/dd/yy HH:mm} ]").

<appender name="RollingLogFileAppender"
          type="log4net.Appender.RollingFileAppender">
  <file value="C:\somelog" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <datePattern value="-yyyy-MM-dd'.txt'" />
  <layout type="log4net.Layout.PatternLayout">
    <header value="[START:  %date{MM/dd/yy HH:mm} ]&#13;&#10;" />
    <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} - %message" />
    <footer value="[END]&#13;&#10;&#13;&#10;" />
  </layout>
</appender>

如何获取此信息以在标题中打印日期/时间?

How can I get this to print the date/time in the header?

推荐答案

一种简单的方法是将log4net.Layout.PatternLayout子类化并覆盖Header和Footer.然后,您可以在标题中添加任何内容:日期戳,计算机名称,用户名,程序集版本,或任何您想要的内容:

An easy way to do this is to subclass log4net.Layout.PatternLayout and override Header and Footer. Then you can add whatever you want to your Header: date stamp, machine name, user name, assembly version, or whatever your heart desires:

using System;
using log4net.Layout;

namespace MyAssembly
{
    class MyPatternLayout : PatternLayout
    {
        public override string Header
        {
            get
            {
                var dateString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                return string.Format("[START:  {0} ]\r\n", dateString);
            }
        }
    }
}

将此新类包含在程序集中,并在文件中使用新类型,如下所示:

Include this new class in your assembly, and use the new type in your file, like this:

<layout type="MyAssembly.MyPatternLayout">
    <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} - %message" />
</layout>

由于您覆盖了页眉和页脚,因此甚至无需在此处添加它.每次您的应用程序启动和文件翻转时,都会添加标头.

Since you overrode Header and Footer, you don't even need to add it here. The Header will be added every time your application starts, and every time the file rolls over.

这篇关于如何在页眉/页脚中使用日期模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆