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

时间:2018-02-16 02:03:20

标签: c# io streamwriter file-writing 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); 
}

2 个答案:

答案 0 :(得分:1)

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

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

这里的初学者教程

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

log4net允许您登录文件,数据库,控制台和自定义' appenders'。

答案 1 :(得分:0)

这是使用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

相关问题