简体   繁体   English

记录Visual Studio MVC5

[英]Logging Visual Studio MVC5

I am working on a project that is a web application. 我正在开发一个作为Web应用程序的项目。 The application should have a single button on the page that redirects the user back to the same page. 该应用程序应该在页面上具有一个按钮,该按钮可将用户重定向回同一页面。 In 1 of every 5 (or thereabout) occasions when you press the button the program should throw some exception and log it. 在每五(或大约)五次之一中,当您按下按钮时,程序应该抛出一些异常并将其记录下来。

It should catch the exception and do three things: Send an email, write the error in a file and write it to debug window. 它应该捕获异常并执行三件事:发送电子邮件,将错误写入文件,然后将其写入调试窗口。

My controller so far: 到目前为止,我的控制器是:

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            try
            {
                RedirectToAction("Index");
            }
            catch (ArgumentException e)
            {

            }
            Random RandNumber = new Random();
            int rand = RandNumber.Next(1000);
            if(rand % 5 == 0)
            {
                throw new System.ArgumentException("This is a random excpetion");
            }
            return View();
        }

    }

The idea is the to have the class Logger that declares a collection of the class LogMedia and loops through all the instances. 想法是让类Logger声明类LogMedia的集合并遍历所有实例。

Class Logger: 类记录器:

  public class Logger
    {
        List<LogMedia> m_loggers = new List<LogMedia>();
        void LogException(Exception ex)
        {
            foreach(var i in m_loggers)
            {
                //Loop through all Log Media instances
            }
        }

Class LogMedia 类LogMedia

    class LogMedia
    {
        public virtual void LogMessage(string Message); //virtual function that doesen't do anything

    }
    class OutputWindowLogMedia:LogMedia
    {
        public override void LogMessage(string Message)
        {
            System.Diagnostics.Debug.WriteLine(Message);
        }
    }
    class TextFileLogMedia : LogMedia
    {
        public override void LogMessage(string Message)
        {
            File.AppendAllText("c:\\Temp\\Log.txt", Message);
        }
    }
    class EmailLogMedia : LogMedia
    {
        public override void LogMessage(string Message)
        {
            //send email
        }

    }
}

My questions to you are the following: 我对您的问题如下:

Will my controller work as it stands now with what I am trying to implement? 我的控制器现在可以按照我要实现的方式工作吗? I am especially skeptical of my try catch.. 我对我的尝试感到特别怀疑。

What is the best way to loop though these three instances? 通过这三个实例循环的最佳方法是什么?

Do I have the right class declerations for Log Media, ie should I create new classes(that inherits LogMedia) for each instance and then a function that overrides the virtual function in LogMedia. 我是否对Log Media具有正确的类定义,即是否应该为每个实例创建新的类(继承LogMedia),然后创建一个覆盖LogMedia中的虚拟函数的函数。

It's unclear if you want this behavior on this particular action, the controller, or the entire app. 尚不清楚您是否要在此特定操作,控制器或整个应用程序上执行此操作。 That said, unless there is some specific recovery code you want to build into your logic, I wouldn't pollute my action code with the try-catch. 就是说,除非您要在逻辑中构建一些特定的恢复代码,否则我不会使用try-catch污染我的操作代码。

There are two options the MVC framework provides to handle errors: MVC框架提供了两个选项来处理错误:

First, you can override OnException in a specific controller: 首先,您可以在特定控制器中重写OnException:

protected override void OnException(ExceptionContext filterContext)
{
    // do your logging here
    // set this flag if you want to stop the exception from bubbling
    filterContext.ExceptionHandled = true;
}

Second, you can create an error handling filter: 其次,您可以创建一个错误处理过滤器:

public class MyExceptionFilterAttribute :
    System.Web.Mvc.FilterAttribute, 
    System.Web.Mvc.IExceptionFilter
{
    public void OnException(System.Web.Mvc.ExceptionContext filterContext)
    {
        // same error handling logic as the controller override
    }
}

A filter can either be added to the global filters list, or applied to an action method like this: 过滤器既可以添加到全局过滤器列表中,也可以应用于以下操作方法:

[MyExceptionFilter]
public ActionResult Index()
{
}

Edit: forgot to mention your logger structure. 编辑:忘记提及您的记录器结构。 Your approach of having Logger loop over multiple instances of LogMedia is a good, common approach to supporting multiple logging mechanisms with one common interface (log4net appenders for example). Logger在LogMedia的多个实例上循环的方法是一种很好的通用方法,可以通过一个公共接口(例如log4net附加程序)支持多种日志记录机制。 That said, have you considered using an existing, proven framework for your logging needs? 就是说,您是否考虑过使用现有的,经过验证的框架来满足您的日志记录需求? You get a thoroughly tested framework to run, and a skill that will carry over to future endeavours. 您将获得一个经过全面测试的框架来运行,并且这项技术可以延续到未来的工作中。

Edit2: after your comment, I took a closer look at your code instead of your exception trapping approach. Edit2:在您发表评论之后,我仔细研究了您的代码,而不是您的异常捕获方法。 In your Index action, you're redirecting to Index with no condition checking. 在“索引”操作中,您无需进行条件检查即可重定向到索引。 This is going to end up as a constant redirect loop (until IIS stops you). 这将导致不断的重定向循环(直到IIS阻止您)。 Since this is an assignment, I don't want to give too much away, but you will need some logic on the server side to detect a button click and redirect back to your Index. 由于这是一项任务,因此我不想付出太多,但是您将需要服务器端的一些逻辑来检测按钮的单击并重定向回您的索引。 Consider another Index action method that accepts HttpPost (your current action would be the HttpGet handler). 考虑另一个接受HttpPost的Index操作方法(您当前的操作将是HttpGet处理程序)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM