use*_*174 5 c# logging console-application
我创建了一个控制台应用程序,它从Excel工作表传输数据并将其传输到数据库.我需要登录它.
我该怎么办呢?因为我完全不知道如何去做.
Chi*_*era 13
如果您只想将文本作为日志写入文件,则可以执行以下操作:
string strLogText = "Some details you want to log.";
// Create a writer and open the file:
StreamWriter log;
if (!File.Exists("logfile.txt"))
{
log = new StreamWriter("logfile.txt");
}
else
{
log = File.AppendText("logfile.txt");
}
// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();
// Close the stream:
log.Close();
Run Code Online (Sandbox Code Playgroud)
此代码的来源来自本文.
以下是StreamWriter类的一些文档.
否则,如果你想要更多的东西,你可以像其他人建议的那样做,并查看Log4Net.
I require to do logging into it....
您是说您希望将日志记录添加到应用程序还是希望人们使用log in?
将事物记录到文件Log4Net的存在使您可以轻松实现.如果你不想依赖第三方的东西那么你可以做一些类似的事情
Trace.Listeners.Clear();
if (options.Verbose)
{
var ctl = new ConsoleTraceListener(false) { TraceOutputOptions = TraceOptions.DateTime };
Trace.Listeners.Add(ctl);
}
if (options.Log)
{
var logFileFs = new FileStream("my.log", FileMode.Append);
var twtl = new TextWriterTraceListener(logFileFs)
{ TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime };
Trace.Listeners.Add(twtl);
}
Trace.AutoFlush = true;
Trace.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture) + " My App Started");
Run Code Online (Sandbox Code Playgroud)
这使您可以向输出添加不同的输出,例如日志文件和详细打印,以便您可以登录到文件,并在用户选择使用详细输出时将其打印在控制台中.
这条线
Trace.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture) + " My App Started");
Run Code Online (Sandbox Code Playgroud)
应该成为一个函数,它接收你的消息,也许是一个日志级别,这样你就可以统一查看所有写入的日志消息.
如果您不需要那么多功能,您可以直接写入文件流.
| 归档时间: |
|
| 查看次数: |
37111 次 |
| 最近记录: |