C# 将时间戳添加到 Trace.WriteLine()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/863394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Timestamp to Trace.WriteLine()
提问by
In my C# .NET application I have an issue with the Trace.WriteLine()-method. I uses this method alot, and want to add a TimeStamp every time I use it.
在我的 C# .NET 应用程序中,我遇到了 Trace.WriteLine() 方法的问题。我经常使用这种方法,并且每次使用它时都想添加一个时间戳。
Instead of Trace.WriteLine(DateTime.Now + " Something wrong!"), is there a solution where the DateTime is on default?
而不是 Trace.WriteLine(DateTime.Now + "Something wrong!"),是否有默认 DateTime 的解决方案?
采纳答案by Joel Coehoorn
Just write your own "TraceLine(string msg)
" method and start calling that:
只需编写您自己的“ TraceLine(string msg)
”方法并开始调用它:
void TraceLine(string msg, bool OmitDate)
{
if (!OmitDate)
msg = DateTime.Now + " " + msg;
Trace.WriteLine(msg);
}
void TraceLine(string msg) {TraceLine(msg, false);}
回答by Lloyd
You could write a wrapper method that did it:
您可以编写一个包装方法来做到这一点:
public static void DoTrace(string message)
{
DoTrace(message,true);
}
public static void DoTrace(string message, bool includeDate)
{
if (includeDate) {
Trace.WriteLine(DateTime.Now + ": " + message);
} else {
Trace.WriteLine(message);
}
}
回答by Kai Wang
We use log4net TraceAppender where you can config layout or filtering easily.
我们使用 log4net TraceAppender,您可以在其中轻松配置布局或过滤。
回答by user38309
Via code
通过代码
You can configure the TraceOutputOptions flags enum.
您可以配置 TraceOutputOptions 标志枚举。
var listener = new ConsoleTraceListener() { TraceOutputOptions = TraceOptions.Timestamp | TraceOptions.Callstack };
Trace.Listeners.Add(listener);
Trace.TraceInformation("hello world");
This does not work for Write and WriteLine, you have use the TraceXXX methods.
这不适用于 Write 和 WriteLine,您必须使用 TraceXXX 方法。
Via app.config
通过 app.config
This can also be configured in your App.config with a somewhat equivalent and using TraceSource:
这也可以在你的 App.config 中配置,有点等价并使用 TraceSource:
<configuration>
<system.diagnostics>
<trace autoflush="true">
<sources>
<source name="TraceSourceApp">
<listeners>
<add name="myListener" type="System.Diagnostics.ConsoleTraceListener" traceOutputOptions="Timestamp" />
</listeners>
</source>
</sources>
</trace>
</system.diagnostics>
</configuration>
And in code you can:
在代码中,您可以:
private static TraceSource mySource =
new TraceSource("TraceSourceApp");
static void Main(string[] args)
{
mySource.TraceInformation("hello world");
}
回答by tm1
回答by johara56
You can set the app.config
file to use a timestamp (relative and current time) for all trace listeners using the traceOutputOptions
您可以app.config
使用traceOutputOptions
traceOutputOptions = "DateTime, Timestamp";