locked
serilog not displaying username RRS feed

  • Question

  • User-154169686 posted

    Hi
    I am using serilog with webaip. With every message I would like to add username and class name to every error message.

    I am new to serilog

    public partial class Repo : BaseRepo<db>
    {
    public Repo(ILogger logger) : base(logger)
    {
    Not working
    // Logger.ForContext("UserId", currentuser).ForContext<Repo>();

    }

    Monday, October 8, 2018 2:02 AM

All replies

  • User1120430333 posted

    I am using serilog with webaip. With every message I would like to add username and class name to every error message.

    It seems kind of questionable about a userid known by the WebAPI, unless you are passing in a userid as a parm when calling a WebAPI Action method. 

    Maybe you should be using an Exception Filter as a global exception handler that catches all unhandled exceptions, which means you don't need any try/catches in the WebAPI or any classlib project the WebAPI uses.

    You could use an GUID that is logged with the exception message as an example of identification.

    Here is some sample code about the Exception Filter the controller is using, which is in VB, but you should be able to understand it that was code taken from the link.

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

    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
    
    
            <HttpGet>
            <ActionName("GetProjectsByUserId")>
            public Function GetProjectsByUserId(ByVal userid As String) As List(Of DtoProject)
                return _daoproject.GetProjectsByUserId(userid)
            End Function
    
            <HttpPost>
            <ActionName("CreateProject")>
            public sub CreateProject(ByVal dto As DtoProject)
                Call _daoproject.CreateProject(dto)
            End sub
            
            <HttpPost>
            <ActionName("UpdateProject")>
            public sub UpdateProject(ByVal dto As DtoProject)
                Call _daoproject.UpdateProject(dto)
            End sub
    
            <HttpPost>
            <ActionName("DeleteProject")>
            public sub  DeleteProject(ByVal dto As DtoId)
                Call _daoproject.DeleteProject(dto.Id)
            End sub
            
        End Class
    End Namespace

     

    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
    

    Monday, October 8, 2018 9:44 AM
  • User-271186128 posted

    Hi DevManNZ1981,

    serilog not displaying username

    How do you get the current user information? Please set break point in this method and check whether currentuser is null?

    Besides, here are some related articles about using Serilog, you could refer them to use logger.LogInformation method to add log message.

    https://www.davidhayden.me/blog/asp-net-5-logging-using-serilog-and-rolling-log-file

    https://github.com/serilog/serilog/wiki/Configuration-Basics

    Best regards.
    Dillion

    Tuesday, October 9, 2018 6:11 AM