繁体   English   中英

C#:写入日志文件,而不是Console.WriteLine

[英]c#: write to log file instead of Console.WriteLine

我喜欢如何从程序的任何部分调用Console.Writeline,并将它简单地添加到已有的文本中。 除了写文本文件外,是否有其他方法可以轻松实现?

public int my_function(int A, int B)
{
   string this_line = string.format("total value: {0}", A+B);
   Console.Writeline(this_string) 
}

到目前为止,我的解决方案如下。 它工作正常,但我认为必须有更好的方法。 也许可以通过某种方法在所有函数中访问全局StreamWriter对象,而无需将其传递给它们?

public int my_function(int A, int B)
{
   string this_line = string.format("total value: {0}", A+B);
   File.AppendAllText(logfile_path, this_line); 
}

您应该使用日志框架,例如log4net。

https://logging.apache.org/log4net/

初学者教程在这里

https://www.codeproject.com/Articles/140911/log-net-Tutorial

log4net允许您登录到文件,数据库,控制台和自定义的“ appender”。

这是使用NLog的示例: https : //github.com/NLog/NLog/wiki/Examples

var logger = LogManager.GetCurrentClassLogger();
logger.Target = new FileTarget("path to your log file");
string this_line = string.format("total value: {0}", A+B);
logger.Info(this_line);

或者您可以使用log4net

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM