locked
Serilog + SEQ + Autofac RRS feed

  • Question

  • User-154169686 posted

    I am using serilog & SEQ with Autofac (DI) in my project (MVC/ web api etc). Although it's working fine
    but not sure it's the right way.

    I have few questions. please help

    Q1)How can I make LoggerConfiguration is manage via Web.config (appsetting) such as Verbose/Debug etc.

    Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .Enrich.FromLogContext()
    .WriteTo.Seq(serilogUrl)
    .CreateLogger();

    Q2) With Everymessage I would like to write userid. I have used push propery with out "using" statement.
    see below code

    public partial class Repo : BaseRepo<db>
    {
    public Repo(ILogger logger) : base(logger)
    {
    var currentuser = GetUserName();
    LogContext.PushProperty("User Name", currentuser);
    Logger.ForContext<Repo>();
    }
    public void somefunction()
    {
    try{}
    catch(exception e){
    Logger.Error(e, "Message");
    }
    }
    }

    Q3) In a constructor I have used **Logger.ForContext<Repo>()** assuming this will write class name to each message. but it's not working.

    Logger.ForContext<Repo>()

    Note: I am not using asp.net core/.Net core

    Tuesday, October 9, 2018 3:43 AM

All replies

  • User1120430333 posted

    Note: I am not using asp.net core/.Net core

    Well, just use a Basecontroller and log the exception message  for the MVC solution, doing global exception handling.  You don't need any try/catch anywhere in the code in the presentation UI layer as the basecontroller will catch all unhandled exceptions.

    https://www.code-sample.com/2014/08/base-controller-in-mvc-5.html

    You could assign a GUID to the logged error message and an identification. You can also pass the GUID the Home controller Error view with an user friendly message telling the user about the  GUID as an error message ID in the log.

    About the WebAPI, which is discussed after the MVC code In either case MVC or WebAPI, the  stack trace gives full details about the location of the exception. You can use a GUID ID there too. 

    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using log4net;
    
    namespace MVC.Controllers
    {
        public abstract partial class BaseController : Controller
        {
            private ILog _logger;
    
            protected BaseController()
            {
                _logger =  LogManager.GetLogger(typeof(BaseController));
            }
    
            protected override void OnException(ExceptionContext filterContext)
            {
                AppException appException = new AppException(Convert.ToString(filterContext.Exception))
                {
                    Type = filterContext.GetType().ToString(),
                    StackTrace = filterContext.Exception.StackTrace,
                    Source = filterContext.Exception.Source,
                    InnerException = Convert.ToString(filterContext.Exception.InnerException)
                };
    
                _logger.Error(appException.ToString());
    
                Server.ClearError();
    
                RedirectToControllers("Home", "Error");
            }
    
            private void RedirectToControllers(string control, string action)
            {
                var routeData = new RouteData();
    
                routeData.Values["controller"] = control;
    
                routeData.Values["action"] = action;
    
                IController controller = new HomeController();
    
                ((IController) controller).Execute(new RequestContext(
                    new HttpContextWrapper(System.Web.HttpContext.Current), routeData));
            }
        }
    }
    namespace MVC
    {
        using System;
    
        public class AppException : Exception
        {
            public AppException(String message) : base(message)
            { }
    
            public string Type { get; set; }
            public string StackTrace { get; set; }
            public string InnerException { get; set; }
            public AppException(String message, Exception inner) : base(message, inner) { }
        }
    }


    mespace MVC.Controllers
    {
        public class ProjectController : BaseController
        {
            // GET: Project
            [Authorize]
            public ActionResult Index()
            {
                return View(new ProjectModels().GetProjectsByUserId(User.Identity.GetUserId()));
            }
         }
    }

    You can also do a CustomExecsptioAttribute and again do global exception handling at the WebAPT controller and any code the WebAPI  controller is referencing with no try/catch  being used anywhere as the filter catches all unhandled exceptions.

    https://stackify.com/csharp-catch-all-exceptions/

    The example just happens to be done in VB.NET taken from the C# example in the link.

    Imports System.Net
    Imports System.Net.Http
    Imports System.Web.Http.Filters
    Imports log4net
    
    Public Class CustomExceptionFilter
        Inherits ExceptionFilterAttribute
    
        private ReadOnly _logger As ILog
    
        public sub New()
            _logger = LogManager.GetLogger(GetType(CustomExceptionFilter))
        End sub
    
        Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
            MyBase.OnException(actionExecutedContext)
    
            Dim exceptionMessage as String = String.Empty
    
            If IsNothing(actionExecutedContext.Exception.InnerException ) Then
                exceptionMessage = actionExecutedContext.Exception.Message _
                                   & " " & actionExecutedContext.Exception.StackTrace
            Else 
                exceptionMessage =  actionExecutedContext.Exception.Message _
                                    & " " & actionExecutedContext.Exception.InnerException.Message _
                                    & " " & actionExecutedContext.Exception.StackTrace
            End If
    
            _logger.Error(exceptionMessage)
    
            dim response =  New HttpResponseMessage(HttpStatusCode.InternalServerError)With {.Content = New StringContent(“An unhandled exception was thrown by service.”),
                    .ReasonPhrase = "Internal Server Error.Please Contact your Administrator."}
    
            actionExecutedContext.Response = response
    
        End Sub
    End Class
    
    Imports System.Web.Http
    Imports DAL
    Imports Entities
    
    Namespace Controllers
    
        <CustomExceptionFilter>
        Public Class ProjectController
            Inherits ApiController
    
            Private ReadOnly _daoproject As IDaoProject
    
            public sub New (daoproject As IDaoProject)
                _daoproject = daoproject
            End sub
    
            <HttpGet>
            <ActionName("GetProjectById")>
            public Function GetProjectById(ByVal id As Int32) As DtoProject
                return _daoproject.GetProjectById(id)
            End Function
    
         end class
    
    end namespace

    Tuesday, October 9, 2018 7:30 AM