将log4net添加到动态生成的C#代码中 [英] Add log4net to C# code generated dynamically
问题描述
我们有使用CodeDom编译成库的代码. 在其中一些类中,我想添加log4net语句.
We have code that gets compiled into a library using CodeDom. In some of these classes I would like to add log4net statements.
我不确定将以下行添加到将动态编译的代码中的语法(以便稍后可以在类中使用log对象):
I am not sure about the syntax to add the following line (so that I can use the log object for logs later in the class) into the code that will be compiled dynamically :
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
到目前为止,我在构建代码的类中具有以下内容:
So far I have the following in the class that builds the code:
//create log4net entry
CodeMemberField log4netField = new CodeMemberField(typeof(log4net.ILog), "log");
log4netField.Attributes = MemberAttributes.Static | MemberAttributes.Private;
然后我应该使用InitExpression吗?如:
Should I then use InitExpression? As in:
log4netField.InitExpression = new CodePrimitiveExpression();
我似乎找不到作为声明的一部分为字段分配值的方法,也没有找到将其声明为只读状态的方法.
I can't seem to find how to assign a value to a field as part of the declaration, and I also don't find how I can state it as readonly.
这对您有所帮助: MSDN ,但没有我需要的所有示例.
This has been of some help: MSDN, but it doesn't have examples of everything that I need.
所以,我的主要问题是如何添加它:
So, my main problem is how to add this:
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
我对CodeDom不太了解,但是我怀疑如果将其添加为字符串可能无法正常工作?
I do not know a lot about CodeDom, but I suspect something might not work if I add it as a string?
推荐答案
您可以在核心组件中返回ILog
的方法中声明以下内容:
You could declare the following in a method that returns ILog
in your core components:
return LogManager.GetLogger(new StackTrace().GetFrames()[1].GetMethod().DeclaringType);
然后在像这样动态编译的代码中获取其实例:
And then obtain an instance thereof in the code that gets dynamically compiled like so:
var log = Log.Get();
这样,无论您的代码是通过CodeDom动态编译还是从一开始就在其中,您都将最终获得调用类型的日志记录实例,而不必使用Reflection.
That way, regardless of whether your code is dynamically compiled in via the CodeDom or was in there from the start, you'll always end up with a logging instance for the calling type without having to use Reflection.
我已经在整个代码中使用这种实现近一年了,甚至使用动态编译插件的项目也可以以这种方式处理日志记录,而没有任何明显的副作用.
I've been using this implementation throughout my code for almost a year now, and even projects that use dynamically compiled plugins can handle logging this way without any noticeable side effects.
这篇关于将log4net添加到动态生成的C#代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!