1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【C#】ログを出力したい

Posted at

世の中にごまんとあるが、備忘録として残したっていいじゃない。
log4net.configはプロジェクト直下に配置想定。

設定

AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFile = "log4net.config")]
log4net.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<log4net>
		<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
			<File value=".\log\sample" />
			<appendToFile value="true" />
			<rollingStyle value="composite" />
			<staticLogFileName value="false" />
			<datePattern value='"."yyyy-MM-dd".log"' />
			<MaxSizeRollBackups value="20" />
			<MaximumFileSize value="1MB" />
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%d [%M][%P{addr}][%P{user}] %p : %message%n" />
			</layout>
		</appender>
		<root>
			<level value="ALL" />
			<appender-ref ref="RollingLogFileAppender" />
		</root>
	</log4net>
</configuration>
CS
public class HomeController : Controller
{
    private static readonly log4net.ILog _logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public ActionResult Index()
    {
        log4net.GlobalContext.Properties["addr"] = "addr"; // クライアントのIPを設定する
        log4net.GlobalContext.Properties["user"] = "user"; // クライアントのユーザーIDを設定する
        _logger.Info("メッセージ");
        
        return View();
    }
}

結果

sample.2021-03-29.log
2021-03-29 16:56:54,354 [Index][addr][user] INFO : メッセージ
1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?