简体   繁体   English

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

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

I like how Console.Writeline can be called from any part of a program, and it simply adds to the text already there. 我喜欢如何从程序的任何部分调用Console.Writeline,并将它简单地添加到已有的文本中。 Is there a way to have that same ease but with writing to a text file instead? 除了写文本文件外,是否有其他方法可以轻松实现?

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

My solution so far is below. 到目前为止,我的解决方案如下。 It works fine, but I feel there must be a better way. 它工作正常,但我认为必须有更好的方法。 Maybe some way to have a global StreamWriter object I can access in all functions without passing it to them? 也许可以通过某种方法在所有函数中访问全局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); 
}

You should use a logging framework such as log4net. 您应该使用日志框架,例如log4net。

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

Beginners tutorial here 初学者教程在这里

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

log4net allows you to log to file, database, console and custom 'appenders'. log4net允许您登录到文件,数据库,控制台和自定义的“ appender”。

This is an example using NLog: https://github.com/NLog/NLog/wiki/Examples 这是使用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);

or you can use log4net 或者您可以使用log4net

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

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