user9981099
user9981099

Reputation:

How to get current user from ServiceStack.Logging

I am using ASP.NET MVC and servicestack.logging I used log4net.

I need to get current user who has been authenticated by servicestack-jwt.

With below code in my webconfig, I just get windows current user.

  <appender type="log4net.Appender.RollingFileAppender" name="User_Log">
  <file value="C:\logging\user_log\" />
  <datePattern value="dd.MM.yyyy'.log'" />
  <appendToFile value="true" />
  <rollingStyle value="Composite" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="false" />

  <layout type="log4net.Layout.PatternLayout">
     <header type="log4net.Util.PatternString" value="[START LOG] %newline" />
     <footer type="log4net.Util.PatternString" value="[END LOG] %newline" />
    <conversionPattern value="[%property{log4net:HostName}] - [%username] - [%identity] - [%w] -%identity%newline%utcdate - %-5level - %message%newline" />
  </layout>

I also used below code in Global.asax

       protected void Application_Start()
    {

        ServiceStack.Logging.LogManager.LogFactory = new ServiceStack.Logging.Log4Net.Log4NetFactory(true);

        //I can save test
        Logger.InfoFormat("test");

        string name = "";
        HttpContext context = HttpContext.Current;
        if (context != null && context.User != null && context.User.Identity.IsAuthenticated)
        {
            name = context.User.Identity.Name;
        }
        //I can NOT save name
        _logger.InfoFormat(name);

    }

Any help? Thanks.

Upvotes: 2

Views: 703

Answers (1)

mythz
mythz

Reputation: 143339

In ServiceStack, the Authenticated User is stored in the UserSession which is accessible from IRequest.GetSession(). If using an AppHost like ASP.NET Framework which maintains the current HttpContext in a HttpContext.Current singleton, it can be accessed with:

var req = HostContext.TryGetCurrentRequest();
var session = req.GetSession();
var userName = session.UserAuthName;

Upvotes: 1

Related Questions