Log4Net不会记录自定义异常正确 [英] Log4Net doesn't log custom exception correct

查看:88
本文介绍了Log4Net不会记录自定义异常正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用log4net和记录异常.但是我想在异常时间记录当前对象,但是我不能. 我创建了异常并将对象添加到异常的data属性中,然后通过log4net记录异常. log4net的异常消息不包含我的对象.

I'm using log4net and logging exceptions. but i want to log current object on exception time but i couldn't. I created exception and add object to exception's data property then log exception by log4net. log4net's exceptions message doesn't contain my object.

我的代码,例如;

 try
                {
                    Exception exp = new Exception("critical error");
                    exp.Data.Add("Eror Object", viewModel);
                    throw exp;
                }
                catch (Exception exp)
                {
                    _logManager.Error(exp);

                }

我的viewModel对象;

my viewModel object;

 [Serializable]
    public class CartTransferViewModel
    {
        public CartTransferViewModel()
        {
            Model = new ModelObject();
        }
        public ModelObject Model { get; set; }
        public string InformatinMessage { get; set; }
        public bool? IsActive { get; set; }
    }

我的Model对象也可序列化.但是log4Net的异常消息是这样的;

And my Model object serializable too. but log4Net's exception message like this;

System.Exception: critical error
   at FooProject.FooClass.FooMethod() in d:\FooProject\FooClass.cs:line 200

我要删除可序列化的属性,然后重新运行我的应用程序,错误代码的确更改为;

I'm remove serializable attribute then re run my application, error code did change to;

System.ArgumentException: Argument passed in is not serializable.
Parameter name: value
   at System.Collections.ListDictionaryInternal.Add(Object key, Object value)
   at FooProject.FooClass.FooMethod() in d:\FooProject\FooClass.cs:line 200

如何用我的对象记录我的自定义异常?

How to log my custom exception with my objects?

推荐答案

好,如果我收到您的问题.我做类似的事情.我使用记录器编写异常.但是我使用Exception.Data属性.

Ok ,if i got your question. i do the something similar . i use logger to write the exception . But i use Exception.Data property.

这是示例,示例包含 1)信息类,需要编写 2)带有方法的示例类,发生异常时编写infoclass 3)格式化异常的实用程序类

here is the example , example contains 1) Info class , which needs to be written 2) Sample class with method , write infoclass when exception happens 3) Utility class which formats the exception

 [Serializable]
    public class FlatFileItem
    {
        ArrayList errorlist = new ArrayList();

        public FlatFileItem()
        {
            if (errorlist == null) { errorlist = new ArrayList(); }
        }

        //Name of the file
        public string FileName { get; set; }
        public override string ToString()
        {
            return string.Format(@"FlatFileItem (Unzip FTPLineItem) => FileName:{0}",  this.FileName);
        }
    }


public class someclass {
    public void somemethod(){
        try{
            // throw exception here
        } catch (Exception ex)
                    {
                        ex.Data["flatfile"] = Convert.ToString(flatfile);  //Using data property
                        flatfile.HasErrors = true;  //not there in above example
                        flatfile.Parent.AddErrorInfo(ex); //not there in above example
                        logger.Error(String.Format(ex.Message)); //not there in above example

                        throw ( new Exception ("yourmsg",ex)); //if you want to do this
                    }
    }
}

//现在我使用此实用程序方法在最高级的异常中写出所有内容

//Now i use this utility method to write out everything at very top level exception

 public class ExceptionInfoUtil
{
    public static string GetAllExceptionInfo(Exception ex)
    {
        StringBuilder sbexception = new StringBuilder();

        int i = 1;
        sbexception.Append(GetExceptionInfo(ex, i));

        while (ex.InnerException != null)
        {
            i++;
            ex = ex.InnerException;
            sbexception.Append(GetExceptionInfo(ex, i));
        }

        return sbexception.ToString();
    }

    private static string GetExceptionInfo(Exception ex, int count)
    {
        StringBuilder sbexception = new StringBuilder();
        sbexception.AppendLine(string.Format(""));
        sbexception.AppendLine(string.Format(""));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format(" Inner Exception : No.{0} ", count));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format("=================================================="));
        sbexception.AppendLine(string.Format(" Error Message : {0} ", ex.Message));
        sbexception.AppendLine(string.Format("=================================================="));
        #region Mine Thru data dictionary

        try
        {
            sbexception.AppendLine(string.Format("=================================================="));
            sbexception.AppendLine(string.Format(" Data parameters Count at Source :{0}", ex.Data.Count));
            sbexception.AppendLine(string.Format("=================================================="));

            string skey = string.Empty;
            foreach (object key in ex.Data.Keys)
            {
                try
                {
                    if (key != null)
                    {
                        skey = Convert.ToString(key);
                        sbexception.AppendLine(string.Format(" Key :{0} , Value:{1}", skey, Convert.ToString(ex.Data[key])));
                    }
                    else
                    {
                        sbexception.AppendLine(string.Format(" Key is null"));
                    }
                }
                catch (Exception e1)
                {
                    sbexception.AppendLine(string.Format("**  Exception occurred when writting log *** [{0}] ", e1.Message));
                }
            }
        }
        catch (Exception ex1)
        {
            sbexception.AppendLine(string.Format("**  Exception occurred when writting log *** [{0}] ", ex1.Message));
        }

        #endregion
        sbexception.AppendLine(string.Format("=================================================="));
        sbexception.AppendLine(string.Format(" Source : {0} ", ex.Source));
        sbexception.AppendLine(string.Format("=================================================="));
        sbexception.AppendLine(string.Format(" StackTrace : {0} ", ex.StackTrace));
        sbexception.AppendLine(string.Format("=================================================="));
        sbexception.AppendLine(string.Format(" TargetSite : {0} ", ex.TargetSite));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format(" Finished Writting Exception info :{0} ", count));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format(""));
        sbexception.AppendLine(string.Format(""));

        return sbexception.ToString();

    }
}

这篇关于Log4Net不会记录自定义异常正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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