我正在嘗試將來自服務的請求響應記錄到文本文件中。我正在使用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\\[email protected]\\" + "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 - 好的,我會照顧的。 –