public void sending_logs_to_a_text_file() { LogReceiver r = new LogReceiver(InternalLogPath); r.Invoking(sut => sut.Start()).ShouldNotThrow(); r.Stop(); }
public void sending_log_from_client() { using (var r = LogReceiver.Start()) { RunClient(r.PipeName); Assert.AreEqual(r.WaitEnd(), LogReceiverEndStatus.Normal); } }
public void ClearLog() { LogReceiver.Clear(); ResetLogNumber(); UpdateLogTexts(); UpdateFilteredLog(); }
public void Log(Exception ex, LogReceiver Receiver = LogReceiver.MessageBox | LogReceiver.Console) { string details = string.Format("{0}", ex.ToString()); if (ex is OperationCanceledException) { Receiver = LogReceiver.Console | LogReceiver.StatusBar; } Log(ex.Message, 0, LogMessageType.Failure, Receiver, details); }
public static Log GetLogger(string name) { lock(_loggers.SyncRoot) { if (_loggers.ContainsKey(name)) return _loggers[name] as Log; Log log = new LogReceiver(name); _loggers.Add(name, log); return log; } }
public IDisposable AddReceiver(LogReceiver receiver) { if (receiver == null) throw new ArgumentNullException("receiver"); lock (_receivers) { var guid = _receivers.Count + 1; _receivers.Add(guid, receiver); return new Reference(this, guid); } }
public void AddReceiver(LogReceiver receiver) { if (receiver == null) { throw new ArgumentNullException("receiver"); } lock (_receivers) { _receivers.Add(receiver); } }
/// <summary> /// Creates a <see cref="LogReceiver"/> that logs all output to the console. /// </summary> /// <param name="listenLevel">Max Log Level that we're interested in.</param> /// <returns>A <see cref="LogReceiver"/> instance that was added to the receiver list.</returns> public static LogReceiver AddConsoleReceiver(Level listenLevel) { LogReceiver consoleReceiver = new LogReceiver((Level logLevel, string message) => { // Is this within our log level? if (listenLevel <= logLevel) { Console.WriteLine(message); // Write the mesage } }); AddReceiver(consoleReceiver); return(consoleReceiver); }
/// <summary> /// Creates a <see cref="LogReceiver"/> that logs all output to the immediate window. /// </summary> /// <param name="listenLevel">Max Log Level that we're interested in.</param> /// <returns>A <see cref="LogReceiver"/> instance that was added to the receiver list.</returns> public static LogReceiver AddImmediateReceiver(Level listenLevel) { LogReceiver immediateReceiver = new LogReceiver((Level logLevel, string message) => { // Is this within our log level? if (listenLevel <= logLevel) { System.Diagnostics.Debug.WriteLine(message); // Write the mesage } }); AddReceiver(immediateReceiver); return(immediateReceiver); }
public void RunLogService(IPEndPoint address, Device device, string logName, LogReceiver rcvr) { using (Socket socket = ExecuteRawSocketCommand(address, device, "log:{0}".With(logName))) { byte[] data = new byte[16384]; using (MemoryStream ms = new MemoryStream(data)) { int offset = 0; while (true) { int count; if (rcvr != null && rcvr.IsCancelled) { break; } byte[] buffer = new byte[4 * 1024]; count = socket.Receive(buffer); if (count < 0) { break; } else if (count == 0) { try { Thread.Sleep(WAIT_TIME * 5); } catch (ThreadInterruptedException) { } } else { ms.Write(buffer, offset, count); offset += count; if (rcvr != null) { byte[] d = ms.ToArray(); rcvr.ParseNewData(d, 0, d.Length); } } } } } }
public void Initialize(string exchange_name, string exchange_type) { //Initialize Connection var factory = new ConnectionFactory(); var connection = factory.CreateConnection(); _channel = connection.CreateModel(); _exchange_name = exchange_name; //Initialize exchange _channel.ExchangeDeclare(_exchange_name, exchange_type); //Initialize Reciever _reciever = new LogReceiver(connection, _channel); _reciever.Initialize(); //BindQueue(_exchange_name); }
private async Task Connect(GameServer server) { var log = new LogReceiver( server.ServerConfiguration.LogPort, server.ServerConfiguration.EndPoint ); log.Listen <ChatMessage>(server.ChatReceived); log.Listen <KillFeed>(server.KillReceived); log.Listen <PlayerConnected>(connected => { server.Players.Add(connected.Player); server.ServerInfoUpdated(); }); log.Listen <PlayerDisconnected>(disconnected => { var player = server.Players.FirstOrDefault(p => p.ClientId == disconnected.Player.ClientId); if (player == null) { return; } server.Players.Remove(player); server.ServerInfoUpdated(); }); log.Listen <NameChange>(change => { var player = server.Players.FirstOrDefault(p => p.ClientId == change.Player.ClientId); if (player == null) { return; } player.Name = change.NewName; server.ServerInfoUpdated(); }); server.Connected = true; server.ServerInfoUpdated(); await Task.Delay(-1); }
void OpenHost() { try { MessageType type = MessageType.Error; if (chkDetails.Checked) { type = MessageType.Details; } else { if (chkMessage.Checked) { type = MessageType.Message; } else { if (chkWarning.Checked) { type = MessageType.Warning; } } } _subscriptionId = Client.Subscribe(tbLogReceiver.Text, type); LogReceiver logReceiver = new LogReceiver(); logReceiver.MessageReceived += new MessageReceivedEvent(logReceiver_MessageReceived); logReceiver.ConnectionClosed += new Action(logReceiver_ConnectionClosed); _listenerHost = new ServiceHost(logReceiver, new Uri(tbLogReceiver.Text)); ServiceEndpoint endpoint = _listenerHost.AddServiceEndpoint(typeof(Logging.LogReceiverSoap), _custombindingSoap12, string.Empty); _listenerHost.Open(); EnableControls(true); } catch (Exception exc) { ShowError(exc); } }
public CsServer(string ip, ushort port, string rconPassword, Config config, GuildManager guild, int id) { try { IP = ip; Port = port; RconPassword = rconPassword; Config = config; LogPort = Convert.ToUInt16(config.LogPort); Manager = guild; ID = id; LogReceiver = new LogReceiver(LogPort, new IPEndPoint(IPAddress.Parse(IP), Port)); StartListeners(LogReceiver); } catch (Exception e) { Console.WriteLine($"EXCEPTION: {e}"); } }
/// <summary> /// Creates a <see cref="LogReceiver"/> that logs all output to the specified file. /// </summary> /// <param name="filePath">String containing the output file.</param> /// <param name="listenLevel">Max Log Level that we're interested in.</param> /// <param name="append">If true (default) the file will be appended to if it exists, otherwise the file will be cleared.</param> /// <param name="forceFlush">If true (default) the file stream will be flushed following each write.</param> /// <returns>A <see cref="LogReceiver"/> instance that was added to the receiver list.</returns> public static LogReceiver AddFileReceiver(string filePath, Level listenLevel, bool append = true, bool forceFlush = true) { StreamWriter outStream = new StreamWriter(filePath, append, System.Text.Encoding.Unicode); LogReceiver fileReceiver = new LogReceiver((Level logLevel, string message) => { // Is this within our log level? if (listenLevel <= logLevel) { outStream.WriteLine(message); if (forceFlush) { outStream.Flush(); } } }); AddReceiver(fileReceiver); return(fileReceiver); }
public HomeController() { _logReceiver = new LogReceiver("localhost", "log_queue"); }
/// <summary> /// Runs a log service on the <seealso cref="Device"/>, and provides its output to the <seealso cref="LogReceiver"/>. /// <p/>This call is blocking until <seealso cref="LogReceiver#isCancelled()"/> returns true. </summary> /// <param name="adbSockAddr"> the socket address to connect to adb </param> /// <param name="device"> the Device on which to run the service </param> /// <param name="logName"> the name of the log file to output </param> /// <param name="rcvr"> the <seealso cref="LogReceiver"/> to receive the log output </param> /// <exception cref="TimeoutException"> in case of timeout on the connection. </exception> /// <exception cref="AdbCommandRejectedException"> if adb rejects the command </exception> /// <exception cref="IOException"> in case of I/O error on the connection. </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static void runLogService(java.net.InetSocketAddress adbSockAddr, Device device, String logName, com.android.ddmlib.log.LogReceiver rcvr) throws TimeoutException, AdbCommandRejectedException, java.io.IOException public static void runLogService(EndPoint adbSockAddr, Device device, string logName, LogReceiver rcvr) { SocketChannel adbChan = null; try { adbChan = SocketChannel.open(adbSockAddr); adbChan.configureBlocking(false); // if the device is not -1, then we first tell adb we're looking to talk // to a specific device setDevice(adbChan, device); var request = formAdbRequest("log:" + logName); write(adbChan, request); AdbResponse resp = readAdbResponse(adbChan, false); // readDiagString if (resp.okay == false) { throw new AdbCommandRejectedException(resp.message); } var data = new byte[16384]; ByteBuffer buf = ByteBuffer.wrap(data); while (true) { int count; if (rcvr != null && rcvr.cancelled) { break; } count = adbChan.read(buf); if (count < 0) { break; } else if (count == 0) { Thread.Sleep(WAIT_TIME * 5); } else { if (rcvr != null) { rcvr.parseNewData(buf.array(), buf.arrayOffset(), buf.position); } buf.rewind(); } } } finally { if (adbChan != null) { adbChan.close(); } } }
/// <summary> /// Runs the Event log service on the <seealso cref="Device"/>, and provides its output to the /// <seealso cref="LogReceiver"/>. /// <p/>This call is blocking until <seealso cref="LogReceiver#isCancelled()"/> returns true. </summary> /// <param name="adbSockAddr"> the socket address to connect to adb </param> /// <param name="device"> the Device on which to run the service </param> /// <param name="rcvr"> the <seealso cref="LogReceiver"/> to receive the log output </param> /// <exception cref="TimeoutException"> in case of timeout on the connection. </exception> /// <exception cref="AdbCommandRejectedException"> if adb rejects the command </exception> /// <exception cref="IOException"> in case of I/O error on the connection. </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static void runEventLogService(java.net.InetSocketAddress adbSockAddr, Device device, com.android.ddmlib.log.LogReceiver rcvr) throws TimeoutException, AdbCommandRejectedException, java.io.IOException public static void runEventLogService(EndPoint adbSockAddr, Device device, LogReceiver rcvr) { runLogService(adbSockAddr, device, "events", rcvr); //$NON-NLS-1$ }
/// <summary> /// Runs the Event log service on the Device, and provides its output to the LogReceiver. /// </summary> /// <param name="address">The address.</param> /// <param name="device">The device.</param> /// <param name="logName">Name of the log.</param> /// <param name="rcvr">The RCVR.</param> /// <exception cref="AdbException">failed asking for log</exception> /// <exception cref="Managed.Adb.Exceptions.AdbCommandRejectedException"></exception> public void RunLogService(IPEndPoint address, Device device, String logName, LogReceiver rcvr) { try { using (var adbChan = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { adbChan.Connect(address); adbChan.Blocking = true; // if the device is not -1, then we first tell adb we're looking to talk // to a specific device SetDevice(adbChan, device); var request = FormAdbRequest("log:" + logName); if (!Write(adbChan, request)) { throw new AdbException("failed asking for log"); } var resp = ReadAdbResponse(adbChan, false /* readDiagString */); if (resp.Okay == false) { throw new AdbCommandRejectedException(resp.Message); } byte[] data = new byte[16384]; using (var ms = new MemoryStream(data)) { int offset = 0; while (true) { int count; if (rcvr != null && rcvr.IsCancelled) { break; } var buffer = new byte[4 * 1024]; count = adbChan.Receive(buffer); if (count < 0) { break; } else if (count == 0) { try { Thread.Sleep(WAIT_TIME * 5); } catch (ThreadInterruptedException ie) { } } else { ms.Write(buffer, offset, count); offset += count; if (rcvr != null) { var d = ms.ToArray( ); rcvr.ParseNewData(d, 0, d.Length); } } } } } } finally { } }
/// <summary> /// Runs the Event log service on the Device, and provides its output to the LogReceiver. /// </summary> /// <param name="address">The address.</param> /// <param name="device">The device.</param> /// <param name="rcvr">The RCVR.</param> public void RunEventLogService(IPEndPoint address, Device device, LogReceiver rcvr) { RunLogService(address, device, "events", rcvr); }
/// <summary> /// Runs the log service. /// </summary> /// <param name="logname">The logname.</param> /// <param name="receiver">The receiver.</param> public void RunLogService(String logname, LogReceiver receiver) { AdbHelper.Instance.RunLogService(AndroidDebugBridge.SocketAddress, this, logname, receiver); }
/// <summary> /// Example program for CoreRCON. /// </summary> internal static void Main(string[] args) { var task = Task.Run(async() => { var ip = "192.168.1.8"; // "162.248.93.211"; // var endpoint = new IPEndPoint( IPAddress.Parse(ip), 27015 ); var rcon = new RCON(endpoint, "rcon"); var log = new LogReceiver(0, endpoint); var players = await ServerQuery.Players(endpoint); var info = await ServerQuery.Info(endpoint, ServerQuery.ServerType.Source) as SourceQueryInfo; Console.WriteLine($"Connected to server with {players.Length} players. Map is {info.Map} in game {info.Game} running on {info.Environment}"); // Tell the server to send logs here await rcon.SendCommandAsync($"logaddress_add 192.168.1.8:{log.ResolvedPort}"); rcon.OnDisconnected += () => { Console.WriteLine("Server closed connection!"); }; var status = await rcon.SendCommandAsync <Status>("status"); Console.WriteLine($"Got status, hostname is: {status.Hostname}"); // Listen for chat messages log.Listen <ChatMessage>(chat => { Console.WriteLine($"Chat message: {chat.Player.Name} said {chat.Message} on channel {chat.Channel}"); }); // Listen for kills log.Listen <KillFeed>(kill => { Console.WriteLine($"Player {kill.Killer.Name} ({kill.Killer.Team}) killed {kill.Killed.Name} ({kill.Killed.Team}) with {kill.Weapon}"); }); log.Listen <PlayerConnected>(connection => { Console.WriteLine($"Player {connection.Player.Name} connected with host {connection.Host}"); }); log.Listen <PlayerDisconnected>(dis => { Console.WriteLine($"Player {dis.Player.Name} disconnected"); }); log.Listen <NameChange>(name => { Console.WriteLine($"{name.Player.Name} changed name to {name.NewName}"); }); // Never stop await Task.Delay(-1); }); // .Wait() puts exceptions into an AggregateException, while .GetResult() doesn't task.GetAwaiter().GetResult(); }
public LogProvider(LogReceiver receiver) { this.Receiver = receiver; }
public SendLogJob(LogReceiver receiver) { ReceiverLog += receiver; }
/// <summary> /// Removes the given <see cref="LogReceiver"/> to the list of log message /// receivers. /// </summary> /// <param name="receiver">The <see cref="LogReceiver"/> that is no longer interested in receiving /// log messages.</param> public static void RemoveReceiver(LogReceiver receiver) { Log(Level.Debug, "Removing log receiver: {0} in {1}.", receiver.Method.Name, receiver.Method.DeclaringType.FullName); logReceivers.Remove(receiver); }
public void Remove(LogReceiver receiver) { lock (_receivers) _receivers.Remove(receiver); }
private void StartListeners(LogReceiver logReceiver) { logReceiver.Listen <ChatMessage>(chat => { ProcessChatMessage(chat); }); logReceiver.Listen <RoundEndScores>(roundEndScore => { if (Match.IsLive) { Match.CTScore = roundEndScore.CTScore + Match.CtSwapScore; Match.TScore = roundEndScore.TScore + Match.TSwapScore; if (Match.CTScore + Match.TScore == 15 || ((Match.CTScore + Match.TScore) > 29 && (Match.CTScore + Match.TScore) % 3 == 0)) { Match.CtSwapScore = Match.TScore; Match.TSwapScore = Match.CTScore; } if ((Match.CTScore + Match.TScore) == 15 || Match.ShouldSwapSides(Match.CTScore + Match.TScore)) { Match.SwapSides(); Match.Paused = true; ProcessSwapSides(); } ProcessScoreUpdate(); } }); logReceiver.ListenRaw(result => { ProcessRaw(result); }); logReceiver.Listen <KillFeed>(e => { }); logReceiver.Listen <MatchLive>(live => { Match.MapName = live.MapName; Match.IsLive = true; ProcessMatchStarting(Match); }); logReceiver.Listen <CTTeamName>(ctSide => { Match.CTName = ctSide.CTName; }); logReceiver.Listen <TTeamName>(tSide => { Match.TName = tSide.TName; }); logReceiver.Listen <StartFreezeTime>(startfreezeTime => { Match.IsFreezeTime = true; }); logReceiver.Listen <EndFreezeTime>(endFreezeTime => { if (Match.Paused == true) { ProcessUnpauseMatch(); } Match.IsFreezeTime = false; Match.Paused = false; }); logReceiver.Listen <MatchEnd>(matchEnd => { Console.WriteLine(matchEnd.MatchId); ProcessMatchEnd(matchEnd.MatchId); Match.EndMatch(); }); }
/// <summary> /// Adds the given <see cref="LogReceiver"/> to the list of log message /// receivers. /// </summary> /// <param name="receiver">A <see cref="LogReceiver"/> pointing to a method interested in receiving /// log messages.</param> public static void AddReceiver(LogReceiver receiver) { logReceivers.Add(receiver); Log(Level.Debug, "Added log receiver: {0} in {1}.", receiver.Method.Name, receiver.Method.DeclaringType.FullName); }
/// <summary> /// Runs the event log service. /// </summary> /// <param name="receiver">The receiver.</param> public void RunEventLogService(LogReceiver receiver) { AdbHelper.Instance.RunEventLogService(AndroidDebugBridge.SocketAddress, this, receiver); }
public void RunCatLog(IPEndPoint address, IDevice device, string filePath, LogReceiver receiver) { if (device.IsOnline && (receiver != null)) { int num = 0x1400; Action action = null; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0)); socket.ReceiveTimeout = -1; socket.ReceiveBufferSize = num + 1; socket.Blocking = true; socket.Connect(AndroidDebugBridge.SocketAddress); if (action == null) { action = delegate { if (socket != null) { socket.Close(); } }; } receiver.CancelAction = action; this.SetDevice(socket, device); //byte[] data = Instance.FormAdbRequest(string.Format("shell:cat {0}", filePath)); byte[] data = Instance.FormAdbRequest(string.Format("log:{0}", filePath)); if (!this.Write(socket, data)) { throw new AdbException("failed submitting shell command"); } AdbResponse response = Instance.ReadAdbResponse(socket, false); if (!response.IOSuccess || !response.Okay) { throw new AdbException("sad result from adb: " + response.Message); } byte[] buffer = new byte[num + 1]; byte num2 = 0; while ((device.IsOnline && (receiver != null)) && !receiver.IsCancelled) { int num3 = socket.Receive(buffer); if (num3 > 0) { using (MemoryStream stream = new MemoryStream()) { for (int i = 0; i < num3; i++) { if ((((num3 > (i + 1)) && (buffer[i] == 13)) && (buffer[i + 1] == 10)) || ((num2 == 13) && (buffer[i] == 10))) { stream.WriteByte(10); i++; } else { stream.WriteByte(buffer[i]); } if (i == (num3 - 1)) { num2 = buffer[i]; } } receiver.ParseNewData(stream.ToArray(), 0, (int)stream.Length); //continue; } } } } catch (SocketException exception) { if (exception.SocketErrorCode != SocketError.ConnectionAborted) { Log.e("Socket error while receiving response", exception); } } finally { if (socket != null) { socket.Dispose(); } } } }
private async void Start() { //Let's start the listener on our listen port. Allow all IPs from the server list. _ = _logHandler.LogMessage($"Starting SRCDSLogService on {_port}", channel: false); _logReceiver = new LogReceiver(_port, CreateIpEndPoints()); await Task.Run(() => { if (_dataService.RSettings.ProgramSettings.Debug) { _logReceiver.ListenRaw(msg => { Console.WriteLine($"RAW LOG FROM {_logReceiver.lastServer.Address}: " + msg); }); } _logReceiver.Listen <GenericCommand>(genericCommand => { HandleIngameCommand(_logReceiver.lastServer, genericCommand); }); }); //We are going to use this loop to make sure log services are still running. Should they fail, we will tear //down and rebuild. while (true) { bool portBound = IPGlobalProperties.GetIPGlobalProperties() .GetActiveUdpListeners().Any(p => p.Port == _port); if (!portBound) { if (_restartCount < RESTART_LIMIT) { try { _logReceiver.Dispose(); } catch (Exception e) { await _logHandler.LogMessage($"Attempted dispose, but had an issue.\n{e}", alert : true, color : LOG_COLOR); } _restartCount++; //Restart the service Start(); await _logHandler.LogMessage($"Log service has been restarted {_restartCount} times!", color : LOG_COLOR); //Reset the retry count in 15 minutes after the first issue //I expect the log service to die sometimes for whatever reason. if (_restartCount == 0) { _ = Task.Run(async() => { await Task.Delay(TimeSpan.FromMinutes(15)); _restartCount = 0; }); } } else { await _logHandler.LogMessage($"The SrcdsLogService has restarted over {RESTART_LIMIT} in the last 15 minutes. " + $"I will not restart the service again.", alert : true, color : LOG_COLOR); } return; } //Hol up for a bit before rechecking await Task.Delay(5000); } }
public void Log(string Message, int MessageId, LogMessageType MessageType = LogMessageType.Information, LogReceiver Receiver = LogReceiver.MessageBox | LogReceiver.Console, string Details = null) { string timeStamp = DateTime.Now.ToString(); if (Receiver.HasFlag(LogReceiver.Console)) { ListViewItem logItem = new ListViewItem(); string iconName = null; string levelName = null; _detailsList.Add(Details); switch (MessageType) { case LogMessageType.Exclamation: iconName = "exclamation"; levelName = Resources.Messages.Exclamation; break; case LogMessageType.Warning: iconName = "warning"; levelName = Resources.Messages.Warning; break; case LogMessageType.Success: iconName = "success"; levelName = Resources.Messages.Success; break; case LogMessageType.Failure: iconName = "failure"; levelName = Resources.Messages.Failure; break; default: iconName = "information"; levelName = Resources.Messages.Information; break; } logItem.Name = (_detailsList.Count - 1).ToString(); logItem.ImageKey = iconName; logItem.Text = levelName; logItem.SubItems.Add(Message); logItem.SubItems.Add(MessageId != 0 ? MessageId.ToString() : ""); logItem.SubItems.Add(timeStamp); LogList.BeginInvoke(new Action(() => { try { LogList.Items.Add(logItem); if (LogList.Items.Count > 1) { LogList.EnsureVisible(LogList.Items.Count - 1); } } catch (Exception) { } })); } if (Receiver.HasFlag(LogReceiver.StatusBar)) { Color foreColor = Color.Black; switch (MessageType) { case LogMessageType.Warning: foreColor = Color.Orange; break; case LogMessageType.Failure: case LogMessageType.Exclamation: foreColor = Color.Red; break; default: foreColor = Color.Black; break; } LogList.BeginInvoke(new Action(() => { StatusBarLabel.Text = Message; StatusBarLabel.ForeColor = foreColor; })); if (MessageType == LogMessageType.Information || MessageType == LogMessageType.Success) { } } if (Receiver.HasFlag(LogReceiver.MessageBox)) { MessageBoxIcon icon; string title; switch (MessageType) { case LogMessageType.Failure: icon = MessageBoxIcon.Error; title = Resources.Messages.Failure; break; case LogMessageType.Warning: icon = MessageBoxIcon.Warning; title = Resources.Messages.Warning; break; default: icon = MessageBoxIcon.Information; title = Resources.Messages.Information; break; } AlertBox.Show(Message, title, icon, Details); } }
public void RunEventLogService(IPEndPoint address, IDevice device, LogReceiver rcvr) { Device d = (Device)device; AdbHelper.Instance.RunEventLogService(address, d, rcvr); }