可以在" initializeData"中添加时间戳。在TraceListener?
这样的事情:
finally {
if(outStream != null) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
throw new Exception(e);
}
}
我想在启动应用程序后将DateTime.Now放在每个日志中。
答案 0 :(得分:1)
.config文件无法做到这一点。为此,请从代码中创建TraceListener:
//Remove all existing trace listeners
while (Trace.Listeners.Count > 0)
Trace.Listeners.RemoveAt(0);
//Add the new one with new file name
Trace.Listeners.Add(new DelimitedListTraceListener(@"mylogwithdatetime.log"));
答案 1 :(得分:1)
这在某种程度上是可能的。 无论你输入什么" initializeData "转到自定义跟踪侦听器的构造函数。所以如果你有这样的东西
namespace MyLogger
{
public class DebugListener :TraceListener
{
string LogFileName;
public DebugListener (string filename)
{
filename = filename.Replace("@date",DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString());
LogFileName = filename;
}
}
}
和配置
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="dbgListener" type="MyLogger.DebugListener,MyLogger" initializeData="MyLog@date.txt"/>
</listeners>
</trace>
</system.diagnostics>
然后您将获得 MyLog20173.txt 之类的文件名 虽然记住构造函数只会被调用一次,你必须重新启动应用程序来创建一个新的日志,但你总是可以在你的代码中处理这个逻辑,就像每个月创建一个新的日志文件一样
//get new log file name every month
string newFileName = string.Format("{0}_{1}{2}.txt","name",DateTime.UtcNow.Year.ToString(CultureInfo.InvariantCulture),DateTime.UtcNow.ToString("MM", CultureInfo.InvariantCulture))`;