[英]C# server logging to text file from console
I currently have a client which is communicating with a server on localhost. 我目前有一个与localhost上的服务器通信的客户端。 When the client communicates with the server, the server keeps track of what is happening, eg.
当客户端与服务器通信时,服务器会跟踪正在发生的事情,例如。
string response = "Location updated for " + uname + ": " + uloc;
Console.WriteLine(response);
I am trying to keep a log of whatever the server console is listing by writing it out to the text file declared like so in the "public class". 我试图通过将其写到在“公共类”中声明的文本文件中来记录服务器控制台列出的所有内容。
public static System.IO.StreamWriter serverlog = new System.IO.StreamWriter("serverlog.txt", true);
I tried adding a writeline to the txt file as shown below. 我尝试将写入行添加到txt文件,如下所示。
string response = "Location updated for: " + commands[0];
Console.WriteLine(response);
serverlog.WriteLine("[" + DateTime.Now.ToString("h:mm:ss tt") + "] [Server]: " + response);
serverlog.close();
However, when I try to write to serverlog.txt again after serverlog.close();
但是,当我尝试在
serverlog.close();
之后再次写入serverlog.txt时serverlog.close();
is executed, it completely screws up the program, and no command from client to server can be executed again unless the program is re-run from Visual Studio. 如果执行该命令,则会完全破坏该程序,除非从Visual Studio重新运行该程序,否则无法再次执行从客户端到服务器的命令。 How do I re open the streamwriter again so I can append to the text file while the server is still running?
如何再次打开流编写器,以便可以在服务器仍在运行时附加到文本文件?
Let me know if more of my code is needed. 让我知道是否需要更多代码。
Thanks in advance. 提前致谢。
EDIT: 编辑:
static void WriteToLog(string logtext)
{
System.IO.File.AppendAllText("nserverlog.txt", string.Format("{0}{1}", logtext, Environment.NewLine));
}
WriteToLog("[" + DateTime.Now.ToString("h:mm:ss tt") + "] [Server]: " + response);
Once you close the serverlog
object, you have to re-open it every time you want to use it. 关闭
serverlog
对象后,每次要使用它时都必须重新打开它。 Rather than go through that whole mess, just use the File
class: 而不是一团糟,只需使用
File
类:
System.IO.File.AppendAllText(filepath, "text to write");
That will handle all the streamwriting etc. internally. 那将在内部处理所有的streamwriting等。 Nothing to instantiate, nothing to close.
无需实例化,也无需关闭。
I suggest you create some sort of logging class that has a writeToLog(String)
method. 我建议您创建一种具有
writeToLog(String)
方法的日志记录类。 Inside that method, you could write to the console and to the log file and to anywhere else you want, rather than explicitly doing both every time. 在该方法内部,您可以写入控制台,日志文件以及所需的任何其他位置,而不必每次都明确地进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.