Log4Net ErrorFormat と Error の両方を同時に使用する方法

拡張メソッドを作成できます:

namespace log4net.Core
{
    public class Log4NetExtensions 
    {    
         public static void ErrorFormatEx(this ILog logger, string format, Exception exception, params object[] args) 
         {
               logger.Error(string.Format(format, args), exception);
         }
    }
}

その後、他の Log4Net と同じように使用できます メソッド:

Log.ErrorFormatEx("Message {0}", exception, CustomerId);

これはすでに回答されていることを知っておいてください。ただし、この代替手段が役立つと思われる他のユーザー向けです。 log4net メソッドとロジックを「一元化」するために、ILog インターフェイスとログ クラスを作成しました。また、"Error" メソッド用に複数のオーバーロードを作成しました。

ILog.cs

public interface ILog
{
    void Error(Exception exception);
    void Error(string customMessage, Exception exception);
    void Error(string format, Exception exception, params object[] args);
    void Warn(Exception exception);
    void Info(string message);
}

Log.cs

public class Log : ILog
{
    public void Error(Exception exception)
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(exception.TargetSite.DeclaringType);
        logger.Error(exception.GetBaseException().Message, exception);
    }

    public void Error(string customMessage, Exception exception)
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(exception.TargetSite.DeclaringType);
        logger.Error(customMessage, exception);
    }

    public void Error(string format, Exception exception, params object[] args)
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(exception.TargetSite.DeclaringType);
        logger.Error(string.Format(format, args), exception);
    }

    public void Warn(Exception exception)
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(exception.TargetSite.DeclaringType);
        logger.Warn(exception.GetBaseException().Message, exception);
    }

    public void Info(string message)
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        logger.Info(message);
    }
}

使用例

public MyClass DeserializeJsonFile(string path)
{
    try
    {
        using (StreamReader r = new StreamReader(path))
        {
            string json = r.ReadToEnd();
            return JsonConvert.DeserializeObject<MyClass>(json);
        }
    }
    catch (Exception ex)
    {       
        this.log.Error("Error deserializing  jsonfile. FilePath: {0}", ex, path);
        return null;                
    }
}

これは文字列補間で解決されました:

Log.Error($"Message {CustomerId}", myException);