You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在ASP.NET MVC 5 .NET Standard Framework 4.7.1中启用日志功能?

Adding Logging to ASP.NET MVC 5 (.NET 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:

  1. Install the NuGet Package
    Open the Package Manager Console and run:

    Install-Package log4net
    
  2. Add a log4net Configuration File
    Create a new file named log4net.config in 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).

  3. Initialize log4net
    Add this line to your AssemblyInfo.cs (under Properties folder) to load the config on startup:

    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
    
  4. 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:

  1. Install NuGet Packages
    Run these commands in the Package Manager Console:

    Install-Package NLog.Web
    Install-Package NLog.Config
    
  2. Configure NLog
    The NLog.config file 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".

  3. Initialize NLog
    Update your Global.asax.cs Application_Start method:

    using NLog.Web;
    
    protected void Application_Start()
    {
        // Initialize NLog
        NLog.Web.NLogBuilder.ConfigureNLog("NLog.config");
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        // ... other startup code
    }
    
  4. 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:

  1. Configure Trace Listeners in Web.config
    Add this section to your Web.config to 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>
    
  2. Log Messages
    Use Trace static 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 logs folder 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

火山引擎 最新活动