Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

aspnet-sessionId not working for Asp.Net Core (.Net 4.7) #153

Closed
digitaldias opened this issue Jun 10, 2017 · 20 comments
Closed

aspnet-sessionId not working for Asp.Net Core (.Net 4.7) #153

digitaldias opened this issue Jun 10, 2017 · 20 comments
Labels

Comments

@digitaldias
Copy link

We are trying to use aspnet-sessionid in an ASP.Net core application (.net version 4.7) and nLog is not showing it in the logs at all.

We tried with multiple different configuration values, but none produce any output.

Is this supposed to be working in ASP.Net Core and .Net 4.7?

For reference:

In Startup.cs

        public IServiceProvider ConfigureIoC(IServiceCollection services)
        {
            var container = new Container(new RuntimeRegistry());
            container.Configure(config => config.Populate(services));
            services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, HttpContextAccessor>();
            return container.GetInstance<IServiceProvider>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            //loggerFactory.AddDebug();
            loggerFactory.AddNLog();
            env.ConfigureNLog("nlog.config");
            app.UseMvc();
        }

nLog.config file

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLogEntry.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogEntryLevel="Warn"
      internalLogEntryFile="c:\temp\internal.txt">
  <extensions>
    <add assembly="NLog.Web" />
  </extensions>
  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <!--<target xsi:type="File" name="allFile" fileName="c:\temp\nlog-all-${shortdate}.log"
            layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />-->

    <target xsi:type="File" name="allFile" fileName="c:\temp\nlog-all-${shortdate}.json">
      <layout xsi:type="JsonLayout" includeAllProperties="false">
        <attribute name="timeStamp" layout="${longdate}" />
        <attribute name="sessionId" layout="${aspnet-request-ip}" />
        <attribute name="level" layout="${level:upperCase=true}" />
        <attribute name="source" layout="${logger}" />
        <attribute name="message" layout="${message}" />
        <attribute name="exception" layout="${exception}" />
      </layout>
    </target>

    <!--<target xsi:type="File" name="ownFile" fileName="c:\temp\nlog-own-${shortdate}.log"
            layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />-->

    <target xsi:type="File" name="ownFile" fileName="c:\temp\nlog-own-${shortdate}.json">
      <layout xsi:type="JsonLayout" includeAllProperties="false">
        <attribute name="timeStamp" layout="${longdate}" />
        <attribute name="aspnet" layout="Hello ${aspnet-request-ip}" />

        <attribute name="sessionId" layout="${aspnet-sessionid}" />
        <attribute name="level" layout="${level:upperCase=true}" />
        <attribute name="source" layout="${logger}" />
        <attribute name="message" layout="${message}" />
        <attribute name="exception" layout="${exception}" />
      </layout>
    </target>

    <target xsi:type="Null" name="blackHole" />
  </targets>

  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allFile" />

    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackHole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile" />
  </rules>
</nlog>
@304NotModified
Copy link
Member

304NotModified commented Jun 10, 2017

we're using:

var service = GetService<IHttpContextAccessor>()
var sessionid = service.HttpContext.Session.SessionID:

https://github.com/NLog/NLog.Web/blob/master/NLog.Web.AspNetCore/LayoutRenderers/AspNetSessionIdLayoutRenderer.cs#L31

does that one show the correct value in your program?

@304NotModified
Copy link
Member

Closing this due to inactivity. Please let us know if this still an issue and please provide the requested info.

@ricardoalbarracin
Copy link

where using

var service = GetService()
var sessionid = service.HttpContext.Session.SessionID:

@digitaldias
Copy link
Author

This is still an issue. A reply to the OP would be nice :)

@304NotModified
Copy link
Member

When using this line in your code

https://github.com/NLog/NLog.Web/blob/master/NLog.Web.AspNetCore/LayoutRenderers/AspNetSessionIdLayoutRenderer.cs#L31

does that one show the correct value in your program?

@EliiseS
Copy link

EliiseS commented Jul 25, 2017

Where are you supposed to be able to call that method? Context is not set as an instance of a object.

@304NotModified
Copy link
Member

do you use app.UseSession(); ?

Where are you supposed to be able to call that method?

AFAIK HttpContext.Session.SessionId in your controller. Does that yield a sessionid?

@EliiseS
Copy link

EliiseS commented Jul 26, 2017

Does the app in app.UseSession(); refers to Microsoft.AspNetCore.Builder.IApplicationBuilder found in the Startup.cs class under public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)?

If so:
5>Startup.cs(55,17,55,27): error CS1061: 'IApplicationBuilder' does not contain a definition for 'UseSession' and no extension method 'UseSession' accepting a first argument of type 'IApplicationBuilder' could be found (are you missing a using directive or an assembly reference?)

For reference, this is in .NET Core.

@304NotModified
Copy link
Member

Which .net core version? This was build for .net core 1

@EliiseS
Copy link

EliiseS commented Jul 26, 2017

.NET Core using ASP.NET framework 4.7

@304NotModified
Copy link
Member

.net core 1?

@EliiseS
Copy link

EliiseS commented Jul 26, 2017

Yes

@304NotModified
Copy link
Member

@304NotModified
Copy link
Member

@EliiseS
Copy link

EliiseS commented Aug 6, 2017

var context = _httpContextAccessorr.HttpContext; var id= context.Session.Id;

This produces a session ID. However, <attribute name="sessionId" layout="${aspnet-sessionid}" is still not producing anything.

@304NotModified
Copy link
Member

could you post the details of all the nlog.*.dll files? Thanks!

e.g.

image

@304NotModified
Copy link
Member

You're missing `

//add NLog.Web
app.AddNLogWeb();

?

See https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-(csproj---vs2017)

@304NotModified
Copy link
Member

I assume your question has been answered, if not, let us know!

@Defee
Copy link
Contributor

Defee commented Jun 13, 2019

Hi @304NotModified !

I use the wrapper class to log the data in the database, obviously for some of the layers aspnet-sessionid will not be available, is there a workaround to check context in layout if it is null to display empty value/or friendly message for logs, else display session Id.
It happens on the Db target I use.

<target name="dbTarget" xsi:type="Database" 
              connectionString="Your Connection" 
              keepConnection="true" 
              commandText="YourSchema.SaveLogEvent 
                @timeStamp,
                @level, 
                @username, 
                @logger, 
                @url, 
                @machineName,
                @threadId,
                @sessionId,
                @referrer,
                @userAgent,
                @code,
                @message">
        <parameter name="@timeStamp" layout="${date}" />
        <parameter name="@level" layout="${level}" />
        <parameter name="@username" layout="${aspnet-user-identity}" />
        <parameter name="@logger" layout="${logger}" />
        <parameter name="@url" layout="${aspnet-request-url:IncludeHost=true:IncludePort=true:IncludeQueryString=true:IncludeScheme=true}" />
        <parameter name="@machineName" layout="${machinename}" />
        <parameter name="@threadId" layout="${threadid}" />
        <parameter name="@sessionId" layout="${aspnet-sessionid}" />
        <parameter name="@referrer" layout="${aspnet-request-referrer}" />
        <parameter name="@userAgent" layout="${aspnet-request-useragent}" />
        <parameter name="@code" layout="${event-context:item=Code}" />
        <parameter name="@message" layout="${message}" />
      </target>

I really appreciate help as want o get rid of the Object reference is not set as an instance of a object exception in internal nlog logs.

The common wrapper class will throw the exception when you have a Data Access Layer and you call logger in it as it doesn't have a clue about HttpContext.

@304NotModified
Copy link
Member

Please open a new issue and fill in the template, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants