我正在使用:WebSocketSharp-https://github.com/sta/websocket-sharp
以及以下代码作为我的p2pserver的一部分:
public void Listen()
{
var server = new WebSocketServer(P2PPort);
server.Log.Output += (d, s) => { };
server.AddWebSocketService<P2PServerSocketBehavior>("/", bhv =>
{
bhv.OnConnection += (s, e) => ConnectSocket(e.Socket);
bhv.OnException += (s, e) => CloseSocket(e.Socket, e.Message);
bhv.OnDisconnect += (s, e) => CloseSocket(e.Socket, e.Reason);
});
server.Log.Output += (d, s) => { };
server.Start();
server.Log.Output += (d, s) => { };
Console.WriteLine($"Listening for peer-to-peer connections on port {P2PPort}");
ConnectToPeers();
}
private void ConnectToPeers()
{
PeerAddresses.ForEach(peer =>
{
var socket = new WebSocket(peer);
socket.Log.Output += (d, s) => { };
socket.OnOpen += (s, e) => ConnectSocket(socket);
socket.OnError += (s, e) => CloseSocket(socket, e.Message);
socket.OnClose += (s, e) => CloseSocket(socket, e.Reason);
socket.Log.Output += (d, s) => { };
socket.Connect();
socket.Log.Output += (d, s) => { };
});
}
正如您在上面看到的,我正在尝试禁用控制台日志记录,如下所述:https://github.com/sta/websocket-sharp/issues/368
尽管事实我仍然收到错误日志:
我已将问题隔离到websocket-sharp中的此代码中:
private static void defaultOutput(LogData data, string path)
{
var log = data.ToString();
Console.WriteLine(log);
if (path != null && path.Length > 0)
writeToFile(log, path);
}
private void output(string message, LogLevel level)
{
lock (_sync)
{
if (_level > level)
return;
LogData data = null;
try
{
data = new LogData(level, new StackFrame(2, true), message);
_output(data, _file);
}
catch (Exception ex)
{
data = new LogData(LogLevel.Fatal, new StackFrame(0, true), ex.Message);
Console.WriteLine(data.ToString());
}
}
}
在第一个函数中注释“ Console.WriteLine”可以解决该问题。
因此,根据上述情况,尽管出于某种原因,尽管已明确设置其值,但_output仍保留为defaultOutput。
我的要求是能够在使用WebSocketSharp的Nuget包时禁用日志记录(因此我不能真正注释内部代码)。我想我这里确实缺少一些简单的东西。
//编辑1
如果我处理了将消息实际发送到控制台的消息,它会出现两次,这意味着不会替换默认操作。
server.Log.Output += (d, s) =>
{
Console.WriteLine(d.ToString());
};
答案 0 :(得分:0)
我以骇客的方式解决了它:
public static void Disable(this Logger logger)
{
var field = logger.GetType().GetField("_output", BindingFlags.NonPublic | BindingFlags.Instance);
field?.SetValue(logger, new Action<LogData, string>((d, s) => { }));
}
答案 1 :(得分:0)
从GitHub:https://github.com/sta/websocket-sharp
#if DEBUG
// To change the logging level.
httpsv.Log.Level = LogLevel.Trace;
#endif