How to add logging to Grapevine #121
-
Hey, I am using your app from Unity game engine and the server logs are not showing up. I am assuming I need to pass it a custom logger to redirect the logged messages to Unitys logger. I managed to do that with the old version of Grapevine, but not able to figure out how to do it here, could you please provide an example? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Unlike previous version, Grapevine doesn't have a custom logging implementation, relying instead on the Microsoft logging and dependency injection abstractions to provide loggers where needed. In this example, I'll use NLog, but Serilog can also be used.
First, we create a startup class, and configure our logging: public class Startup
{
public IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddNLog(new NLogLoggingConfiguration(Configuration.GetSection("NLog")));
});
}
} Since we are using NLog, we will also need to add the configuration to {
"NLog":{
"internalLogLevel":"Info",
"internalLogFile":"c:\\temp\\internal-nlog.txt",
"extensions": [
{ "assembly": "NLog.Extensions.Logging" }
],
"targets":{
"log-file":{
"type":"File",
"fileName":"c:\\temp\\grapevine-sample-${shortdate}.log",
"layout":"${longdate}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|${all-event-properties}"
},
"log-console":{
"type":"Console",
"layout":"${longdate}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|${all-event-properties}"
}
},
"rules":[
{
"logger":"*",
"minLevel":"Trace",
"writeTo":"log-file"
},
{
"logger":"*",
"minLevel":"Info",
"writeTo":"log-console"
}
]
}
} Next, we use it to create our rest server using the var server = RestServerBuilder.From<Startup>().Build(); Now we can easily inject a logger into our route classes. [RestResource(BasePath = "api")]
public class HelloResource
{
private readonly ILogger<HelloResource> _logger;
public HelloResource(ILogger<HelloResource> logger)
{
_logger = logger;
}
[RestRoute("Get", "/hello")]
public async Task HelloWorld(IHttpContext context)
{
_logger.LogTrace("{requestName} : Hello, world!", context.Request.Name);
await context.Response.SendResponseAsync("Hello, world!");
}
} |
Beta Was this translation helpful? Give feedback.
Unlike previous version, Grapevine doesn't have a custom logging implementation, relying instead on the Microsoft logging and dependency injection abstractions to provide loggers where needed. In this example, I'll use NLog, but Serilog can also be used.
First, we create a startup class, and configure our logging: