简体   繁体   中英

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. 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?

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.

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

Beginners tutorial here

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

log4net allows you to log to file, database, console and custom 'appenders'.

This is an example using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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