1: using System;
2: using System.Web;
3: using System.IO;
4: using MBNCSUtil;
5: using System.Text;
6:
7: /// <summary>
8: /// Summary description for LogFilter
9: /// </summary>
10: public class LogFilter : Stream
11: {
12: private Stream _logStream, _sink, _binaryStream;
13: private StreamWriter _binaryWriter;
14: public LogFilter(HttpContext context, Stream baseStream)
15: {
16: _logStream = File.OpenWrite(
17: Path.Combine(
18: context.Server.MapPath("~/logs"),
19: string.Concat(DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss"), ".txt")
20: )
21: );
22:
23: WriteHeadersToLog(_logStream, "Request Headers", context.Request.Headers);
24:
25: _binaryStream = File.OpenWrite(
26: Path.Combine(
27: context.Server.MapPath("~/logs"),
28: string.Concat(DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss"), "-binary.txt")
29: )
30: );
31: _binaryWriter = new StreamWriter(_binaryStream, Encoding.UTF8);
32: _sink = baseStream;
33: }
34:
35: private static void WriteHeadersToLog(Stream logStream, string title, System.Collections.Specialized.NameValueCollection nameValueCollection)
36: {
37: StreamWriter sw = new StreamWriter(logStream);
38: sw.WriteLine(title);
39: sw.WriteLine();
40: foreach (string name in nameValueCollection.AllKeys)
41: {
42: string value = nameValueCollection[name];
43: if (value == null)
44: value = "(nil)";
45: else if (value.Length == 0)
46: value = "(empty string)";
47:
48: sw.WriteLine("{0}: {1}", name, value);
49: }
50: sw.WriteLine();
51: sw.Flush();
52: }
53:
54: public override bool CanRead
55: {
56: get { return false; }
57: }
58:
59: public override bool CanSeek
60: {
61: get { return false; }
62: }
63:
64: public override bool CanWrite
65: {
66: get { return true; }
67: }
68:
69: public override void Flush()
70: {
71: _logStream.Flush();
72: _sink.Flush();
73: _binaryStream.Flush();
74: }
75:
76: public override long Length
77: {
78: get { return _sink.Length; }
79: }
80:
81: public override long Position
82: {
83: get
84: {
85: return _sink.Length;
86: }
87: set
88: {
89: throw new InvalidOperationException();
90: }
91: }
92:
93: public override int Read(byte[] buffer, int offset, int count)
94: {
95: throw new InvalidOperationException();
96: }
97:
98: public override long Seek(long offset, SeekOrigin origin)
99: {
100: throw new InvalidOperationException();
101: }
102:
103: public override void SetLength(long value)
104: {
105: _sink.SetLength(value);
106: }
107:
108: public override void Write(byte[] buffer, int offset, int count)
109: {
110: _sink.Write(buffer, offset, count);
111: _logStream.Write(buffer, offset, count);
112: string text = DataFormatter.Format(buffer);
113: _binaryWriter.WriteLine(text);
114: }
115:
116: public override void Close()
117: {
118: base.Close();
119: _logStream.Close();
120: _sink.Close();
121: _binaryWriter.Close();
122: _binaryStream.Close();
123: }
124: }