MikeD
MikeD

Reputation: 301

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); 
}

Upvotes: 0

Views: 5847

Answers (2)

Arsslen Idadi
Arsslen Idadi

Reputation: 26

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

Upvotes: 0

RR.
RR.

Reputation: 677

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

Upvotes: 1

Related Questions