【问题标题】:c#: write to log file instead of Console.WriteLinec#:写入日志文件而不是 Console.WriteLine
【发布时间】:2018-02-16 02:03:20
【问题描述】:

我喜欢如何从程序的任何部分调用 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); 
}

【问题讨论】:

  • 小心多线程问题。
  • 你应该使用日志框架。
  • 重定向?在命令行中调用程序时添加>> FileToRedirect.txtMyRoutine.exe >> c:\MyFile.txt甚至MyRoutine.exe >> c:\Log.txt 2>> c:\Errors.txt(将stdoutstderr重定向到不同的文件中)

标签: c# io streamwriter file-writing console.writeline


【解决方案1】:

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

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

这里是初学者教程

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

log4net 允许您记录到文件、数据库、控制台和自定义“附加程序”。

【讨论】:

  • Serilog 比 imo 更好
  • 谢谢,没看到。会看看
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2022-12-29
    • 1970-01-01
    • 2017-07-02
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多