如何在ASP.NET MVC 5 .NET Standard Framework 4.7.1中启用日志功能?
Hey Adam, I totally get your frustration—most modern logging tutorials fixate on .NET Core, but .NET Framework 4.7.1 still has robust, battle-tested logging options. Let’s break down the most practical approaches for your MVC 5 project:
Option 1: log4net (Widely Used & Flexible)
log4net is a stalwart in .NET Framework logging, with tons of customization options. Here’s how to set it up:
Install the NuGet Package
Open the Package Manager Console and run:Install-Package log4netAdd a log4net Configuration File
Create a new file namedlog4net.configin your project root with this basic setup (adjust outputs as needed):<?xml version="1.0" encoding="utf-8" ?> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs/app.log" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="5" /> <maximumFileSize value="10MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> <root> <level value="INFO" /> <appender-ref ref="ConsoleAppender" /> <appender-ref ref="RollingFileAppender" /> </root> </log4net>Don’t forget to set this file’s Copy to Output Directory property to "Copy if newer" (right-click the file → Properties).
Initialize log4net
Add this line to yourAssemblyInfo.cs(under Properties folder) to load the config on startup:[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]Use It in Controllers
Inject the logger into your controller and start logging:using log4net; public class HomeController : Controller { private static readonly ILog _logger = LogManager.GetLogger(typeof(HomeController)); public ActionResult Index() { _logger.Info("Home/Index page loaded"); _logger.Warn("This is a warning message"); _logger.Error("An error occurred!", new Exception("Sample exception")); return View(); } }
Option 2: NLog (Lightweight & Easy to Configure)
NLog is another popular choice with simple setup and great performance:
Install NuGet Packages
Run these commands in the Package Manager Console:Install-Package NLog.Web Install-Package NLog.ConfigConfigure NLog
TheNLog.configfile will be added automatically—tweak it to your needs (here’s a basic version):<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true"> <targets> <target name="console" xsi:type="Console" /> <target name="file" xsi:type="File" fileName="logs/nlog-${shortdate}.log" layout="${longdate} ${level} ${message} ${exception:format=ToString}" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="console,file" /> </rules> </nlog>Again, set Copy to Output Directory to "Copy if newer".
Initialize NLog
Update yourGlobal.asax.csApplication_Startmethod:using NLog.Web; protected void Application_Start() { // Initialize NLog NLog.Web.NLogBuilder.ConfigureNLog("NLog.config"); AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); // ... other startup code }Log in Controllers
Use the logger like this:using NLog; public class HomeController : Controller { private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); public ActionResult Index() { _logger.Info("Home page accessed"); _logger.Error("Error in Index action", new Exception("Test error")); return View(); } }
Option 3: System.Diagnostics (No External Dependencies)
If you don’t want to add third-party packages, use .NET’s built-in System.Diagnostics:
Configure Trace Listeners in Web.config
Add this section to yourWeb.configto set up file logging:<system.diagnostics> <trace autoflush="true" indentsize="4"> <listeners> <add name="fileListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="logs/trace.log" /> <remove name="Default" /> </listeners> </trace> </system.diagnostics>Log Messages
UseTracestatic methods in your controller:using System.Diagnostics; public class HomeController : Controller { public ActionResult Index() { Trace.TraceInformation("Index page loaded at {0}", DateTime.Now); Trace.TraceWarning("Low memory warning"); Trace.TraceError("Critical error occurred!", new Exception("Sample exception")); return View(); } }Note: You’ll need to manually create the
logsfolder in your output directory, or configure the listener to create it automatically.
Quick Tips
- Always set configuration files to copy to the output directory—this is a common pitfall.
- Adjust log levels (Info, Warn, Error, Debug) based on your needs; Debug logs are great for development but should be turned off in production.
- For more advanced scenarios, you can integrate logging with dependency injection (using Unity, Autofac, etc.) to avoid static logger instances.
内容的提问来源于stack exchange,提问作者Adam




