为什么我的应用程序总是在日志文件不存在时崩溃? [英] Why does my app always crash when the log file does not exist?

查看:108
本文介绍了为什么我的应用程序总是在日志文件不存在时崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建的日志文件,如果它不存在,第一次被引用:



I've got a log file that's created, if it doesn't exist, the first time it is referenced:

if (!File.Exists(logPath))
{
    _fileStream = File.Create(logPath);
}





然而,如果文件不存在,应用程序将崩溃,过于通用的异常消息msg,应用程序bla遇到了严重的错误,必须关闭



然后它有问题的文件(里面没有任何内容),所以随后尝试运行应用程序就好了。为什么JIT创建的文件没有在众所周知的传递中解决这个问题?以下是上下文中的代码(整个日志记录类):





Yet if the file doesn't exist, the app will crash with the overly generic exception msg, "Application bla encountered a serious error and must shut down"

It then has the file in question (with nothing in it), so subsequent attempts to run the app go just fine. Why does not the JIT creating of the file cut this problem off at the proverbial pass? Here is the code in context (the entire logging class):

using System;

namespace HHS
{
    using System.IO;
    using System.Text;

    public class ExceptionLoggingService
    {
        // Singleton code
        // private fields
        private readonly FileStream _fileStream;
        private readonly StreamWriter _streamWriter;
        private static ExceptionLoggingService _instance;
        // public property
        public static ExceptionLoggingService Instance
        {
            get
            {
                return _instance ?? (_instance = new ExceptionLoggingService());
            }
        }
        //private constructor
        private ExceptionLoggingService()
        {
            const int MAX_FILESIZE_ALLOWED = 40000;
            string uriPath = GetExecutionFolder() + "\\Application.log";
            string logPath = new Uri(uriPath).LocalPath;
            // If the log file does not exist, the app fails with a cryptic err msg (even with this code!)
            if (!File.Exists(logPath))
            {
                _fileStream = File.Create(logPath);
            }
            FileInfo f = new FileInfo(logPath);
            long fileSizeInBytes = f.Length;
            if (fileSizeInBytes > MAX_FILESIZE_ALLOWED) 
            {
                File.Delete(logPath);
            }
            _fileStream = File.OpenWrite(logPath);
            _streamWriter = new StreamWriter(_fileStream);
        }
        // </ Singleton code

        ~ ExceptionLoggingService()
        {
            if (null != _fileStream)
            {
                _fileStream.Close();
                _fileStream.Dispose();
            }
            if (null != _streamWriter)
            {
                _streamWriter.Close();
                _streamWriter.Dispose();
            }
        }

        public void WriteLog(string message)
        {
            if (!HHSConsts.Logging) return;
            StringBuilder formattedMessage = new StringBuilder();
            formattedMessage.AppendLine("Date: " + DateTime.Now.ToString());
            formattedMessage.AppendLine("Message: " + message);
            _streamWriter.WriteLine(formattedMessage.ToString());
            _streamWriter.Flush();
        }

        private string GetExecutionFolder()
        {
            return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); 
        }

    }
}





为什么缺少文件导致处理这种可能性的问题?



Why does the file being missing cause a problem when that possibility is being handled?

推荐答案

第一次创建时尝试处理文件流



try to dispose the file stream when you create it first time

if (!File.Exists(logPath))
            {
                using (_fileStream = File.Create(logPath)){};
            }


你不认为这是一个非常自然的矛盾:使用日志记录机制,你可以收集所有可能揭示的信息你的错误,但如果你在登录时犯了错误怎么办?



显然,解决方案是:在进行调试之前,提前开发并调试好日志记录机制使用它的更复杂的东西。这些工具已经为你完成。



一个是类 System.Diagnostic.EventLog

http://msdn.microsoft .com / zh-CN / library / system.diagnostics.eventlog%28v = vs.110%29.aspx [ ^ ]。



另一个是众所周知且广泛使用的产品Apache Log4Net:

http://en.wikipedia .org / wiki / Log4j #Ports [ ^ ],

http://logging.apache.org/log4net [ ^ ]。



也许你可以用别的东西......



-SA
Don't you think that this is a very natural contradiction: with the logging mechanism, you can collect all the information which could reveal your bugs, but what if you make a bug in logging itself?

Apparently, the solution is: develop and well debug logging mechanism in advance, before you get to debugging something more complex using it. Such tools are already done for you.

One is the class System.Diagnostic.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog%28v=vs.110%29.aspx[^].

Another one is well known and widely used product Apache Log4Net:
http://en.wikipedia.org/wiki/Log4j#Ports[^],
http://logging.apache.org/log4net[^].

Maybe you can use something else…

—SA


if (!File.Exists(logPath))
{
	_fileStream = File.Create(logPath);
	_fileStream.Dispose();
	
}


这篇关于为什么我的应用程序总是在日志文件不存在时崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆