azure - How to add logs in asp.net vNext -
i need set logs in asp.net application. it's easy add output console, need configure in azure. don't know how it. need log information occurs app file , read it.
the iloggerfactory
allows app use implementation of ilogger
, iloggerprovider
.
for details on how implement interfaces properly, @ framework's consolelogger
, consoleloggerprovider
. see asp.net core documentation on logging.
here minimal example of custom ilogger
started. this not production code, rather, demos enough technical depth either write own ilogger
or use 1 community.
project.json
"dependencies": { "microsoft.aspnet.mvc": "6.0.0-rc1-final", "microsoft.aspnet.server.kestrel": "1.0.0-rc1-final", "microsoft.extensions.logging": "1.0.0-rc1-final", "microsoft.extensions.logging.console": "1.0.0-rc1-final" }
myloggingprovider.cs
namespace loggingexample { using microsoft.extensions.logging; public class myloggingprovider : iloggerprovider { public ilogger createlogger(string categoryname) { return new mylogger(); } public void dispose() { // todo cleanup } } }
mylogger.cs
in azure want write somewhere other c:/temp/some-guid.txt
. enough started, though, writing own simple logger.
namespace loggingexample { using system; using microsoft.extensions.logging; public class mylogger : ilogger { public void log(loglevel loglevel, int eventid, object state, exception exception, func<object, exception, string> formatter) { var builder = new stringbuilder(); if (formatter != null) { builder.appendline(formatter(state, exception)); } var values = state ilogvalues; if (values != null) { foreach (var v in values.getvalues()) { builder.appendline(v.key + ":" + v.value); } } var logpath = string.format("c:/temp/{0}.txt", guid.newguid()); file.writealltext(logpath, builder.tostring()); } public bool isenabled(loglevel loglevel) { return true; } public idisposable beginscopeimpl(object state) { return null; } } }
startup.cs
now in startup can use add logger via loggerfactory.addprovider(new myloggingprovider())
. every call ilogger
log provider.
namespace loggingexample { using microsoft.aspnet.builder; using microsoft.aspnet.http; using microsoft.extensions.logging; public class startup { public void configure( iapplicationbuilder app, iloggerfactory loggerfactory) { loggerfactory .addconsole(minlevel: loglevel.verbose) .addprovider(new myloggingprovider()); app.run(async (context) => { var logger = loggerfactory.createlogger("catchall"); logger.loginformation("hello logger!"); await context.response.writeasync("hello world!"); }); } } }
mycontroller.cs
anywhere supports dependency injection can receive ilogger
log of providers registered in startup.configure
method.
namespace loggingexample { using microsoft.aspnet.mvc; using microsoft.extensions.logging; public class mycontroller : controller { public mycontroller(ilogger logger) { logger.loginformation("logging controller"); } } }
Comments
Post a Comment