在wcf项目的根目录下放置log4net.config配置文件,我这里并将其配置为(按自己需求更改配置):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<!--Log4net Begin by Tony 2008.11.20-->
<log4net>
<!--数据日志-->
<appender name="InfoRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<param name="File" value="Log\Info\" />
<param name="AppendToFile" value="true" />
<param name="rollingStyle" value="Date" />
<param name="datePattern" value="yyyy-MM-dd.'Info.log'" />
<param name="staticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n%n%n 记录时间:%date %n日志级别: %-5level %n出错类:%logger %n错误描述:%message %newline%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</filter>
</appender>
<!--错误日志-->
<appender name="ErrorRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<param name="File" value="Log\Error\" />
<param name="AppendToFile" value="true" />
<param name="rollingStyle" value="Date" />
<param name="datePattern" value="yyyy-MM-dd.'error.log'" />
<param name="staticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n%n%n 记录时间:%date %n日志级别: %-5level %n出错类:%logger %n错误描述:%message %newline%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="ERROR" />
</filter>
</appender>
<!--调试日志-->
<appender name="DebugRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<param name="File" value="Log\Debug\" />
<param name="AppendToFile" value="true" />
<param name="rollingStyle" value="Date" />
<param name="datePattern" value="yyyy-MM-dd.'debug.log'" />
<param name="staticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n%n%n 记录时间:%date %n日志级别: %-5level %n出错类:%logger %n错误描述:%message %newline%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="DEBUG" />
</filter>
</appender>
<root>
<level value="DEBUG" />
<!--文件形式记录日志-->
<appender-ref ref="ErrorRollingFileAppender" />
<appender-ref ref="DebugRollingFileAppender" />
<appender-ref ref="InfoRollingFileAppender" />
</root>
</log4net>
<!--Log4net End-->
</configuration>
注:DotNet.Utilities.dll是码云上一个开源.net开发工具类库,项目地址https://gitee.com/kuiyu/dotnetcodes
using log4net;
using System;
using System.Diagnostics;
namespace DotNet.Utilities
{
public static class Log
{
public static void Debug(object message)
{
LogManager.GetLogger(DotNet.Utilities.Log.GetCurrentMethodFullName()).Debug(message);
}
public static void Debug(object message, Exception ex)
{
LogManager.GetLogger(DotNet.Utilities.Log.GetCurrentMethodFullName()).Debug(message, ex);
}
public static void Error(object message)
{
LogManager.GetLogger(DotNet.Utilities.Log.GetCurrentMethodFullName()).Error(message);
}
public static void Error(object message, Exception exception)
{
LogManager.GetLogger(DotNet.Utilities.Log.GetCurrentMethodFullName()).Error(message, exception);
}
public static void Info(object message)
{
LogManager.GetLogger(DotNet.Utilities.Log.GetCurrentMethodFullName()).Info(message);
}
public static void Info(object message, Exception ex)
{
LogManager.GetLogger(DotNet.Utilities.Log.GetCurrentMethodFullName()).Info(message, ex);
}
public static void Warn(object message)
{
LogManager.GetLogger(DotNet.Utilities.Log.GetCurrentMethodFullName()).Warn(message);
}
public static void Warn(object message, Exception ex)
{
LogManager.GetLogger(DotNet.Utilities.Log.GetCurrentMethodFullName()).Warn(message, ex);
}
private static string GetCurrentMethodFullName()
{
StackFrame frame;
string str;
string str1;
bool flag;
try
{
int num = 2;
StackTrace stackTrace = new StackTrace();
int length = stackTrace.GetFrames().Length;
do
{
int num1 = num;
num = num1 + 1;
frame = stackTrace.GetFrame(num1);
str = frame.GetMethod().DeclaringType.ToString();
flag = (!str.EndsWith("Exception") ? false : num < length);
}
while (flag);
string name = frame.GetMethod().Name;
str1 = string.Concat(str, ".", name);
}
catch
{
str1 = null;
}
return str1;
}
}
}
使用第3步的帮助类,向log4net.config中配置的路径文件下打印日志信息,如下:
打开AssemblyInfo.cs程序集,增加一行代码:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
在解决方案的该wcf项目中,增加一个类文件,重写ServiceHostFactory与ServiceHost(需添加引用System.ServiceModel与System.ServiceModel.Activation引用),如下:
using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace LookPictureService
{
public class CustomServiceHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(
Type serviceType, Uri[] baseAddresses)
{
CustomServiceHost customServiceHost =
new CustomServiceHost(serviceType, baseAddresses);
return customServiceHost;
}
}
public class CustomServiceHost : ServiceHost
{
public CustomServiceHost(Type serviceType, params Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{
log4net.Config.XmlConfigurator.Configure();
}
protected override void ApplyConfiguration()
{
base.ApplyConfiguration();
}
}
}
新建一个控制台项目,添加对wcf服务项目的引用,使用代码配置控制台以寄宿wcf服务,如下:
using LookPictureService;
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace TestLookPictureService
{
class Program
{
static void Main(string[] args)
{
// Step 1: Create a URI to serve as the base address.
Uri baseAddress = new Uri("http://localhost:8734/Design_Time_Addresses/LookPictureService/CalculatorService/");
Uri baseAddress1 = new Uri("http://localhost:8734/Design_Time_Addresses/LookPictureService/LookPictureService/");
// Step 2: Create a ServiceHost instance.
ServiceHost selfHost = new CustomServiceHost(typeof(CalculatorService), baseAddress);
ServiceHost selfHost1 = new CustomServiceHost(typeof(LookPictureService.LookPictureService), baseAddress1);
try
{
//修改默认Binding
BasicHttpBinding binding = new BasicHttpBinding();
binding.MaxBufferSize = 2147483647;
binding.MaxReceivedMessageSize = 2147483647;
// Step 3: Add a service endpoint.
selfHost.AddServiceEndpoint(typeof(ICalculator), new BasicHttpBinding(), "CalculatorService");
selfHost1.AddServiceEndpoint(typeof(ILookPictureService), binding, "LookPictureService");//使用修改的的Binding
// Step 4: Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
ServiceMetadataBehavior smb1 = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb1.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
selfHost1.Description.Behaviors.Add(smb1);
// Step 5: Start the service.
selfHost.Open();
selfHost1.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("The service1 is ready.");
// Close the ServiceHost to stop the service.
Console.WriteLine("Press to terminate the service." );
Console.WriteLine("Press to terminate the service1." );
Console.WriteLine();
Console.ReadLine();
selfHost.Close();
selfHost1.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
}
}
}