如何在C#中将控制台输出写入控制台和文件?

时间:2017-12-21 11:16:52

标签: c# console

我有一个简单的控制台应用程序,我在许多地方使用Console.WriteLine向用户显示正在执行的活动。但是,最后我想将所有控制台输出保存到日志文件中。目前,我有这样的事情:

if (!Directory.Exists(LOG_DIRECTORY)) {
    Directory.CreateDirectory(LOG_DIRECTORY);
}

long ticks = DateTime.Now.Ticks;
string logFilename = ticks.ToString() + ".txt";
string filePath = Directory.GetCurrentDirectory() + "\\" + LOG_DIRECTORY + "\\" + logFilename;
FileStream ostream = null;
StreamWriter writer = null;
TextWriter oldOut = Console.Out;

try
{
    ostream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
    writer = new StreamWriter(ostream);
}
catch (Exception ex)
{
    Console.WriteLine("Cannot open {0} for writing.", logFilename);
    Console.WriteLine(ex.Message);
    return;
}

Console.SetOut(writer);

Console.WriteLine("{0}", Directory.GetCurrentDirectory());

Console.SetOut(oldOut);
writer.Close();
ostream.Close();

Console.WriteLine("\n\nDone!");

重点是,这会将内容直接打印到文件中,并且控制台中不会打印任何内容。有没有办法解决这个问题?请注意,我需要将Console.WriteLine输出直接实时写入控制台,而对于写入日志文件,可以在程序结束时完成,其中几乎所有其他内容都是结束。

3 个答案:

答案 0 :(得分:5)

您可以创建自己的组件来写入多个输出,也可以使用NLog等日志记录工具。这可以配置为在<targets>部分中您有类似的内容;

<target name="debugger" xsi:type="Debugger" layout="${level}>${message} (${exception:format=ToString})"/>
<target name="console" xsi:type="ColoredConsole" layout="${date:format=dd-MM-yyyy HH\:mm\:ss} - ${message}" />
<target name="FullCSVFile" xsi:type="File"  fileName="${specialfolder:folder=LocalApplicationData}\YourApp\YourApp-${date:format=yyyy-MM-dd}.csv">
  <layout xsi:type="CsvLayout">
    <column name="Index" layout="${counter}" />
    <column name="ThreadID" layout="${threadid}" />
    <column name="Time" layout="${longdate}" />
    <column name="Severity" layout="${level:uppercase=true}" />
    <column name="Location" layout="${callsite:className=False:fileName=True:includeSourcePath=False:methodName=False}" />
    <column name="Detail" layout="${message}" />
    <column name="Exception" layout="${exception:format=ToString}" />
  </layout>
</target>

然后在rules部分,您有;

<logger name="*" minlevel="Debug" writeTo="console" />
<logger name="*" minlevel="Debug" writeTo="debugger" />
<logger name="*" minlevel="Debug" writeTo="FullCSVFile" />

要实际执行写入操作,您的C#代码中会出现以下内容;

// at a class level;
private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

// later in code that writes to both targets...
_logger.Info("Something happened!");

答案 1 :(得分:1)

如何在string arrayList<string>之类的变量中保存控制台输出?然后执行File.WriteAllText(filepath, consoleOutputArray);

我的意思是这样:

 class Program
    {
        static void Main(string[] args)
        {
            List<string> textStorage = new List<string>();

            string exampleData = "Ford Mustang";

            Console.WriteLine(exampleData);

            SaveOutput(ref textStorage, exampleData);

            System.IO.File.WriteAllLines(@"C://Desktop//MyFolder", textStorage);

        }
        public static void SaveOutput(ref List<string> textStorage, string output)
        {
            textStorage.Add(output);
        }
    }

答案 2 :(得分:0)

在每个控制台输出后,将输出存储在列表中,并在程序结束时更新包含详细信息的日志。

var list = new List<string>;
string xyz = "message";
Console.WriteLine(xyz);
list.add(xyz);
foreach (object o in list)
{
     StreamWriter sw = null;
            String Logfile = "C:\ExceptionLog.txt";
            if (!System.IO.File.Exists(LogFile))
            {
                sw = File.CreateText(LogFile);


            }
            else
            {
                sw = File.AppendText(@"C:\ExceptionLog.txt");
            }

            sw.WriteLine(o);
            sw.Close();
}
相关问题