gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:22:50 25 4
gpt4 key购买 nike

我有一个简单的控制台应用程序,我在许多地方使用了 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 输出直接实时写入控制台,而写入日志文件时,可以在程序结束时完成,几乎所有其他事情都完成了。

最佳答案

您可以创建自己的组件来写入多个输出,也可以使用 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!");

关于c# - 如何在 C# 中将控制台输出写入控制台和文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47923780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com