【发布时间】:2014-07-25 02:09:34
【问题描述】:
我正在尝试将来自服务的请求响应记录到文本文件中。我正在使用 log4net 将响应记录到文本文件,但它只记录请求而不记录响应。 我该怎么做?
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
if (log.IsErrorEnabled)
{
SaveResponseToLog("AfterReceiveReply" +"\n##### VisService SOAP Response #####\n");
string filename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Daimler AG\\Vis@\\" + "log.txt";
System.Xml.XmlDictionaryWriter writer = null;
MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
reply = buffer.CreateMessage();
System.ServiceModel.Channels.Message replyCopy = buffer.CreateMessage();
try
{
FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
writer = System.Xml.XmlDictionaryWriter.CreateTextWriter(fs);
replyCopy.WriteMessage(writer);
MessageBox.Show("AfterReceiveReply" + writer.ToString());
writer.Flush();
}
catch (Exception e)
{
//Something went wrong while writing the response
MessageBox.Show(e.Message);
}
finally
{
writer.Close();
}
}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
{
if (log.IsErrorEnabled)
{
string visServiceSOAPRequest = request.ToString();
log.Error("Error:VisService SOAP Request >>>");
log.Error(visServiceSOAPRequest);
//For displaying the message in the mail confirmation box
SaveResponseToLog("BeforeSendRequest" + "\nVisService SOAP Request >>>\n" + visServiceSOAPRequest);
}
return null;
}
private void SaveResponseToLog(string message)
{
System.IO.StreamWriter writer = null;
//StreamReader rd = null;
string filename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My App\\Application\\" + "log.txt";
if (!File.Exists(filename))
{
using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
fs.Flush();
fs.Close();
}
}
try
{
if (File.Exists(filename))
{
writer = System.IO.File.AppendText(filename);
writer.Write(message);
writer.Flush();
}
}
catch (Exception e)
{
// Wenn das loggen nicht funktioniert, kann der Fehler ja nicht geloggt werden..
log.Error("Error saving the message in the log.txt file: " + e.Message);
}
finally
{
writer.Close();
}
}
【问题讨论】:
-
您可以将
fs和writer包装在using块中,这样就不需要finally,顺便说一句。您还需要清理文件,这对于这样的应用来说听起来很重要。 -
@MatthewHaugen - 好的,我会处理的。