这是主要的program.cs
LogError.WriteError("Application started: " + DateTime.Now + Environment.NewLine);
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CrawlerApp());
}
catch (Exception e)
{
LogError.WriteError(e);
}
LogError.WriteError("Application closed: " + DateTime.Now + Environment.NewLine);
这是LogError类
public static class LogError
{
public static void WriteError(Exception e)
{
WriteError("Message: " + e.Message + Environment.NewLine + "Stack trace: " + e.StackTrace);
}
public static void WriteError(string error)
{
try
{
StreamWriter sw = File.AppendText("log.txt");
sw.WriteLine(DateTime.Now + Environment.NewLine);
sw.WriteLine(error + Environment.NewLine);
sw.WriteLine(Environment.NewLine);
sw.Close();
}
catch (Exception)
{
//
}
}
}
当我发布应用程序并运行它时,永远不会创建log.txt文件。如果我从bin / debug文件夹运行应用程序然后工作。为什么我发布应用程序日志记录不起作用我正在使用win 2003 OS。
答案 0 :(得分:2)
可能是UnauthorizedAccessException。
而不是猜测它你可能想要改变你的捕获以记录到事件日志而不是仅仅吞下它
答案 1 :(得分:0)
File.AppendText仅在文件已存在时才有效:http://msdn.microsoft.com/en-us/library/system.io.file.appendtext.aspx。此链接还包含以下示例代码:
string path = @"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
答案 2 :(得分:0)
您也可以使用此代码,无论文件是否存在,它都有效。作为加号,它基于YYYYMMDD格式的当前DateTime创建日志文件
private static void doLog(String message)
{
//getting current date
String dateStr = "";
int day, month, year;
year = System.DateTime.Now.Year;
month = System.DateTime.Now.Month;
day = System.DateTime.Now.Day;
dateStr += year.ToString() + "";
if (month < 10) dateStr += "0";
dateStr += month.ToString() + "";
if (day < 10) dateStr += "0";
dateStr += day.ToString() + "";
//writting the message
string logFile = Environment.CurrentDirectory + @"/LOG_" + dateStr + @".txt";
System.IO.StreamWriter sw = new System.IO.StreamWriter(logFile, true);
sw.WriteLine(System.DateTime.Now.ToString() + "\t" + message);
sw.Close();
}
答案 3 :(得分:0)
您的日志编写代码可能会引发异常。尝试删除WriteError
中的try / catch以查看抛出的异常。