public void Parse(LogChannel channel, string line) { if (isValidMessage(line)) { int startDate = line.IndexOf("[ ", 0); int endDate = line.IndexOf(" ]", startDate + 2); int endName = line.IndexOf(" > ", endDate + 3); this.channel = channel; string timePart = line.Substring(startDate + 2, endDate - 2).Trim(); bool valid = DateTime.TryParse(timePart, out this.timestamp); this.name = line.Substring(endDate + 2, endName - endDate - 2).Trim(); this.message = line.Substring(endName + 2).TrimStart(); } }
/// <summary> /// Get the given cached channel string name. /// </summary> /// <param name="channel"></param> /// <returns></returns> public static string GetChannelName(LogChannel channel) { return(LogChannels.Channels[(int)channel]); }
public async Task sendToChannel(LogChannel ch, string Message) { await sendToChannel(ch, null, Message); }
public static void Log(LogChannel Level, string message) { Level.Log("[Essentials] " + message); }
public void StartListening(MethodInfo method, Type channel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); HttpListener httpChannel = new HttpListener(); ChannelConfigurationInfo channelConfig = _configuration.Configure(httpChannel, channel, method, _baseURL); //Keep the ChannelMethod open for new requests while (true) { try { httpChannel.Start(); } catch (HttpListenerException hle) { Console.WriteLine($"System.Net.HttpListenerException encountered on {channelConfig.MethodUrl} with reason :{hle.Message}"); return; } Console.WriteLine($"Listening on {channelConfig.MethodUrl}"); HttpListenerContext context = httpChannel.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; IChannelHeuristicContext heuristicsCtx = _services.Get <IChannelHeuristicContext>(); bool executedIfCached = ExecuteIfCached(channel, method, request, response, heuristicsCtx); if (executedIfCached) { heuristicsCtx.Clear(); goto EndRequest; } LogChannel.Write(LogSeverity.Info, $"Request coming to {channelConfig.Endpoint.Name}"); LogChannel.Write(LogSeverity.Info, $"HttpMethod:{request.HttpMethod}"); bool authFailed = AuthenticationFailedIfRequired(context, request, response, channelConfig, out bool authenticated); if (authFailed) { goto EndRequest; } //Check if the Http Method is correct if (channelConfig.HttpMethod.ToString() != request.HttpMethod && channelConfig.HttpMethod != ChannelHttpMethod.Unknown) { _msgService.WrongHttpMethod(response, channelConfig.HttpMethod); LogChannel.Write(LogSeverity.Error, "Wrong HttpMethod... Closing request"); goto EndRequest; } ChannelMethodInfo methodDescription = _channelMethodDescriptor.GetMethodDescription(method); List <object> channelRequestBody = null; ChannelMethodDeserializerFactory dsrFactory = null; if (request.HttpMethod == "GET") { bool invoked = TryInvokeGetRequest(channel, method, request, response, dsrFactory, methodDescription, channelConfig, channelRequestBody, authenticated); goto EndRequest; } //Enter only if Request Body is supplied with POST Method if (request.HasEntityBody == true && request.HttpMethod == "POST") { StreamWriter writer = new StreamWriter(response.OutputStream); try { dsrFactory = new ChannelMethodDeserializerFactory(request.InputStream); channelRequestBody = dsrFactory.DeserializeFromBody(methodDescription, request.ContentType); InitChannelMethodContext(channelConfig.Endpoint, request, response, authenticated, channelConfig.HttpMethod, channelRequestBody); _requestActivator.PostActivate(channel, method, channelRequestBody, response); } catch (ChannelMethodContentTypeException cEx) { response.StatusCode = 400; _msgService.ExceptionHandler(writer, cEx, response); LogChannel.Write(LogSeverity.Error, cEx.Message); } catch (ChannelMethodParameterException pEx) { response.StatusCode = 400; _msgService.ExceptionHandler(writer, pEx, response); LogChannel.Write(LogSeverity.Error, pEx.Message); } catch (TargetParameterCountException tEx) { response.StatusCode = 400; _msgService.ExceptionHandler(writer, tEx, response); LogChannel.Write(LogSeverity.Error, tEx.Message); } catch (Exception ex) { response.StatusCode = 500; _msgService.ExceptionHandler(writer, ex, response); LogChannel.Write(LogSeverity.Fatal, ex.Message); } finally { _contextProvider.DestroyChannelMethodContext(channelConfig.Endpoint); writer.Flush(); writer.Close(); } } EndRequest: LogChannel.Write(LogSeverity.Debug, "Request finished..."); LogChannel.Write(LogSeverity.Debug, "Closing the response"); response.Close(); } }
internal void TryInvokePostRequest(Type channel, MethodInfo method, HttpListenerRequest request, HttpListenerResponse response, List <object> channelRequestBody, ChannelMethodInfo methodDescription, ChannelConfigurationInfo channelConfig, bool authenticated, CacheExecutionResult cacheExecutionResult) { StreamWriter writer = new StreamWriter(response.OutputStream); try { //Since request body will be processed in Heuristics if cache is enabled //InputStream is flushed and data is already stored in Data.Parameters //property of CacheExecutionResult if (!cacheExecutionResult.DataProcessed) { _dsrFactory = new ChannelMethodDeserializerFactory(request.InputStream); channelRequestBody = _dsrFactory.DeserializeFromBody(methodDescription, request.ContentType); } else { channelRequestBody = cacheExecutionResult.Data.Parameters; } InitChannelMethodContext(channelConfig.Endpoint, request, response, authenticated, channelConfig.HttpMethod, channelRequestBody); _requestActivator.PostActivate(channel, method, channelRequestBody, response); } catch (ChannelMethodContentTypeException cEx) { response.StatusCode = 400; _msgService.ExceptionHandler(writer, cEx, response); LogChannel.Write(LogSeverity.Error, cEx.Message); } catch (ChannelMethodParameterException pEx) { response.StatusCode = 400; _msgService.ExceptionHandler(writer, pEx, response); LogChannel.Write(LogSeverity.Error, pEx.Message); } catch (TargetParameterCountException tEx) { response.StatusCode = 400; _msgService.ExceptionHandler(writer, tEx, response); LogChannel.Write(LogSeverity.Error, tEx.Message); } catch (Exception ex) { response.StatusCode = 500; _msgService.ExceptionHandler(writer, ex, response); LogChannel.Write(LogSeverity.Fatal, ex.Message); } finally { _contextProvider.DestroyChannelMethodContext(channelConfig.Endpoint); writer.Flush(); writer.Close(); } }
public static void Log(LogChannel channel, string text) { Write (new LogEntry (text, null) { channel = channel }); }
public static void BareLog(LogChannel channel, string text) { Write (new LogEntry { message = text, thread = Thread.CurrentThread, channel = channel }); }
protected static string FormatMessage(string format, LogLevel level, LogChannel channel, params object[] args) { var message = string.Format(format, args); return(FormatMessage(message, level, channel)); }
public static void LogFormat(string format, LogLevel level = LogLevel.Verbose, LogChannel channel = LogChannel.Debug, params object[] args) { if (levelList.ContainsKey(level) && !levelList[level]) { return; } if ((channels & channel) == LogChannel.None) { return; } var msg = FormatMessage(format, level, channel, args); switch (level) { case LogLevel.Error: Debug.LogError(msg); break; case LogLevel.Warning: Debug.LogWarning(msg); break; case LogLevel.Verbose: case LogLevel.Info: case LogLevel.Dev: default: Debug.Log(msg); break; } LogToolNetwork.Log(msg); }
public static void LogAssertIsFalse(bool predict, string message, LogLevel level = LogLevel.Error, LogChannel channel = LogChannel.Debug) { if (predict) { Log(message, level, channel); } }
public static void AssertNotNull(object obj, LogLevel level = LogLevel.Error, LogChannel channel = LogChannel.Debug) { LogAssertIsTrue(obj != null, System.Environment.StackTrace, level, channel); }
public static void AssertIsFalse(bool predict, LogLevel level = LogLevel.Error, LogChannel channel = LogChannel.Debug) { LogAssertIsFalse(predict, System.Environment.StackTrace, level, channel); }
public static void Enable(LogChannel channel) { channels = channel; }
public static void Enable(LogChannel channel, bool enabled) { channels = enabled ? (channels | channel) : (~channel & channel); }
public static void SetChannelEnabledState(LogChannel channel, bool on) { ChannelsActiveState[(int)channel] = on; }
public static void Log(LogChannel channel, string format, SendingLogger logger, params object[] args) { Write(new LogEntry(format, args) { channel = channel, logger = logger }); }
private void SetLogChannel(LogChannel channel) { if (channel.ChannelName != null) { labelChannel.Text = channel.ChannelName; } else { labelChannel.Text = "Unknown"; } if (channel.Listener != null) { labelListener.Text = channel.Listener; } else { labelListener.Text = "Unknown"; } }
/// <summary> /// Gets all channels, members in them and set's up event handlers /// </summary> /// <param name="guild"></param> /// <returns></returns> internal async Task Initialize(DiscordGuild guild) { //DebugLogWriteLine($"Initiating {guild} GuildTask... "); //Init guild Guild = guild; GuildId = guild.Id; SecretRoomOverwriteBuilder = new DiscordOverwriteBuilder(); SecretRoomOverwriteBuilder.For(Guild.EveryoneRole); SecretRoomOverwriteBuilder.Deny(Permissions.AccessChannels); //PersonalChannelOverwriteBuilder = new DiscordOverwriteBuilder(); //PersonalChannelOverwriteBuilder.Allow(Permissions.AccessChannels); LogChannel = guild.GetChannel(LogChannelId); if (LogChannel != null) { LogMessage = await LogChannel.SendMessageAsync($"Begin of log {DateTime.Now.ToString()}\n"); } //Init RootCategory Guild.Channels.TryGetValue(DateCategoryId, out DiscordChannel cat); if (cat == null) { string m = $"Initialize failed. No Category found on + {DateCategoryId}"; //DebugLogWriteLine(m); throw new Exception(m); } DateRootCategory = cat; Guild.Channels.TryGetValue(DateSecretCategoryId, out DiscordChannel secCat); DateSecretCategory = secCat; //DebugLogWrite("Initiating voice channels... "); //VoiceChannels DateVoiceLobbies.Clear(); SecretRooms.Clear(); DateVoiceLobbies.AddRange(GetVoiceLobbies()); SecretRooms.AddRange(GetSecretRooms()); await VoiceChannelsInitAsync().ConfigureAwait(false); if (DateVoiceLobbies.Count == 0 || DateVoiceLobbies.All(c => c.Users.Count() > 0)) { await AddLastEmptyVoiceLobby().ConfigureAwait(false); } //DebugLogWrite("Initiating Emojis... "); //GetEmojis MaleEmoji = DiscordEmoji.FromUnicode(DateBot.Instance.Client, MaleEmojiId); FemaleEmoji = DiscordEmoji.FromUnicode(DateBot.Instance.Client, FemaleEmojiId); OptionEmojis.Clear(); OptionEmojis.AddRange(OptionEmojiIds.Select(id => DiscordEmoji.FromUnicode(DateBot.Instance.Client, id))); LikeEmoji = DiscordEmoji.FromUnicode(DateBot.Instance.Client, LikeEmojiId); DisLikeEmoji = DiscordEmoji.FromUnicode(DateBot.Instance.Client, DisLikeEmojiId); TimeEmoji = DiscordEmoji.FromUnicode(DateBot.Instance.Client, TimeEmojiId); CancelLikeEmoji = DiscordEmoji.FromUnicode(DateBot.Instance.Client, CancelLikeEmojiId); //DebugLogWrite("Initiating Users in lobbies... "); //Check and add users in lobbies foreach (var u in UsersInLobbies.ToArray()) { AddOrGetUserState(u).LastEnteredLobbyTime = DateTime.Now; } //DebugLogWrite("Initiating Welcome message... "); //Check for welcome message TODO add option emojis DateTextChannel = Guild.GetChannel(DateTextChannelId); await WelcomeMessageInit().ConfigureAwait(false); _ = PrivateControlsMessageInit().ConfigureAwait(false); //UpdateTimer = new Timer(TimeSpan.FromSeconds(30).TotalMilliseconds) { AutoReset = true }; //UpdateTimer.Elapsed += UpdateTimer_Elapsed; //UpdateTimer.Start(); //DebugLogWrite("finished"); InitTask = null; Initialized = true; if (UsersInLobbies.Count > 0) { TryStartMatchingTask(); } }
public void FilterChannel(LogChannel channel) { m_ExtensionChannelFilter.FilterChannel = channel; m_ExtensionContainer.PushLogOverwrite(m_ExtensionChannelFilter); RequireFlush(); }
public LogMessage(LogChannel channel, string line) { this.Parse(channel, line); }
private void CommandFilterChannel(string channel) { FilterChannel(LogChannel.Get(channel)); }
public static void LogAssertionFormat(string format, LogChannel channel, params object[] args) { LogFormat(format, channel, LogLvl.Assertion, args); }
public void SetChannel(LogChannel logChannel) { Channel = logChannel; _text.text = logChannel.Name; }
private bool AuthenticationFailedIfRequired(HttpListenerContext context, HttpListenerRequest request, HttpListenerResponse response, ChannelConfigurationInfo channelConfig, out bool authenticated) { bool failed = false; bool validCookie = false; authenticated = false; bool authorized = false; if (channelConfig.ChannelAttribute.EnableSessions) { validCookie = ValidSession(request); } if (channelConfig.AuthenticationRequired && !validCookie) { try { ChannelAuthenticationContext authContext = new ChannelAuthenticationContext { Context = context, Scheme = channelConfig.AuthScheme, BasicAuthenticationDelegate = _basicAuthenticationMethod, TokenAuthenticationDelegate = _tokenAuthenticationMethod, AuthenticationSettings = _settings }; KeyValuePair <bool, object> authenticationResult = _authenticationService.CheckAuthenticationAndGetResponseObject(authContext); if (authenticationResult.Key == true) { authenticated = true; } else { _msgService.FailedAuthenticationResponse(channelConfig.AuthScheme, response); failed = true; } LogChannel.Write(LogSeverity.Info, "User Authenticated"); string claimName = channelConfig.AuthorizeAttribute.ClaimName; string claimValue = channelConfig.AuthorizeAttribute.ClaimValue; if (!String.IsNullOrEmpty(claimName) && !String.IsNullOrEmpty(claimValue)) { if (authenticationResult.Value.GetType() == typeof(ClaimsPrincipal)) { authorized = _authenticationService.Authorized(claimName, claimValue, (ClaimsPrincipal)authenticationResult.Value); } else { authorized = _authenticationService.Authorized(claimName, claimValue, (Claim[])authenticationResult.Value); } if (!authorized) { _msgService.FailedAuthorizationResponse(response); LogChannel.Write(LogSeverity.Error, "Failed authorization"); failed = true; } else { LogChannel.Write(LogSeverity.Info, "User Authorized"); } } } catch (Exception ex) { using (StreamWriter writer = new StreamWriter(response.OutputStream)) { _msgService.ExceptionHandler(writer, ex, response); LogChannel.Write(LogSeverity.Error, "Authentication Failed"); failed = true; } } if (!authenticated) { failed = true; } else { if (channelConfig.ChannelAttribute.EnableSessions) { string sessionKey = Guid.NewGuid().ToString(); Cookie sessionCookie = new Cookie() { Expires = DateTime.Now.AddMinutes(30), Name = "channelAuthCookie", Secure = true, Value = sessionKey }; response.SetCookie(sessionCookie); _sessionKeys.Add(sessionCookie); } } } return(failed); }
/// <summary> /// Appends log messages to file with timestamp, level and message /// </summary> public void Emit(LogChannel source, LogLevels level, string tag, string message, object[] args) { lock (mutex) { if (paused) return; beginStream(); var msg = string.Format(message, args); stream.WriteLine("{0:g} | [{1}] {2}", DateTime.Now, tag.PadLeft(16, ' '), msg); } }
private void AdvanceCommand(LogS98 Log, SongData sd, TrackData td, CommandData cmd, LogChannel lc) { td.AddWaitTrackTick(cmd.Tick); if (cmd.IsNote) { td.AddStaccato(cmd.Tick); } switch (cmd.Type) { case CommandType.Slur: td.Slur = cmd.Value != 0; break; case CommandType.Octave: td.Octave = cmd.Value; break; case CommandType.OctaveGt: if (!sd.OctaveReverse) { td.Octave++; } else { td.Octave--; } break; case CommandType.OctaveLt: if (!sd.OctaveReverse) { td.Octave--; } else { td.Octave++; } break; case CommandType.Tempo: sd.SetTempo(cmd.Value); break; case CommandType.Tone: SetTone(sd, td, cmd, lc); break; case CommandType.Note: NoteOn(td, lc, cmd.Value + (12 * td.Octave)); break; case CommandType.DirectNote: NoteOn(td, lc, cmd.Value); break; case CommandType.Rest: NoteOff(lc); break; case CommandType.Volume: lc.SetVolume(cmd.Value); break; case CommandType.RepeatStart: td.RepeatStart(cmd.Value); break; case CommandType.RepeatEnd: td.RepeatEnd(cmd.Value); break; case CommandType.Loop: td.SetLoopTick(); Log.SetLoopPoint(); break; case CommandType.Staccato: td.Staccato = (cmd.Value >= 8 ? 0 : cmd.Value); break; default: VerboseWriteLine($"未実装: {cmd}"); break; } }
public static void Log(LogMode mode, string message, Exception ex, string process = "", object data = null) { // Check for an active log channel if (LogChannel == null) { throw new ArgumentNullException("No active log channel! Please enter a valid channel name in to the system configuration table!"); } // Check the log level if (mode < Mode) { return; } // Create the log entry LogRecord logRecord = new LogRecord { LogID = GetNextId().ToString(), Process = process, Host = Environment.MachineName, Level = mode.ToString(), Message = message, Exception = ex, ExceptionString = ex == null ? string.Empty : ex.ToString(), Data = data, DataString = data == null ? string.Empty : JsonConvert.SerializeObject(data), Created = DateTime.UtcNow, TimeStamp = DateTime.UtcNow }; #if NET452 // Set the app key and environment logRecord.AppKey = ConfigurationManager.AppSettings["AppKey"]; logRecord.Environment = ConfigurationManager.AppSettings["Environment"]; // Try to get the host ip try { if (HttpContext.Current != null && HttpContext.Current.Request != null && !string.IsNullOrEmpty(HttpContext.Current.Request.UserHostAddress)) { // Set the host ip logRecord.HostIP = HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]; } } catch { } #elif NETCOREAPP2_2 // Set the app key and environment logRecord.AppKey = _configuration.GetValue <string>("AppKey"); logRecord.Environment = _configuration.GetValue <string>("Environment"); // Try to get the host ip try { if (_httpContextAccessor.HttpContext != null && _httpContextAccessor.HttpContext.Request != null && !string.IsNullOrEmpty(_httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString())) { // Set the host ip logRecord.HostIP = _httpContextAccessor.HttpContext.Connection.LocalIpAddress.ToString(); } } catch { } #endif // Log with the default channel LogChannel.Log(logRecord); }
public async Task sendToChannel(LogChannel ch, Embed embed) { await sendToChannel(ch, embed, ""); }
public static void Log(LogRecord record) { // Check for an active channel if (LogChannel == null) { throw new ArgumentNullException("No log channel! Please enter a valid channel name in to the system configuration table!"); } #if NET452 // Set the app key and environment record.AppKey = ConfigurationManager.AppSettings["AppKey"]; record.Environment = ConfigurationManager.AppSettings["Environment"]; // Try to get the host ip try { if (HttpContext.Current != null && HttpContext.Current.Request != null && !string.IsNullOrEmpty(HttpContext.Current.Request.UserHostAddress)) { // Set the host ip record.HostIP = HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]; } } catch { } #elif NETCOREAPP2_2 // Set the app key and environment record.AppKey = _configuration.GetValue <string>("AppKey"); record.Environment = _configuration.GetValue <string>("Environment"); // Try to get the host ip try { if (_httpContextAccessor.HttpContext != null && _httpContextAccessor.HttpContext.Request != null && !string.IsNullOrEmpty(_httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString())) { // Set the host ip record.HostIP = _httpContextAccessor.HttpContext.Connection.LocalIpAddress.ToString(); } } catch { } #endif // Check the activity id if (String.IsNullOrEmpty(record.LogID)) { record.LogID = GetNextId().ToString(); } // Check the host name if (String.IsNullOrEmpty(record.Host)) { record.Host = Environment.MachineName; } // Check for an incoming exception if (record.Exception != null) { record.ExceptionString = record.Exception.ToString(); } // Check for an incoming data object if (record.Data != null) { record.Data = JsonConvert.SerializeObject(record.Data); } // Override the time stamps record.Created = DateTime.UtcNow; record.TimeStamp = DateTime.UtcNow; // Add the log record LogChannel.Log(record); }
/// <summary> /// Get whether the given channel is active or not. /// </summary> /// <param name="channel"></param> /// <returns></returns> public static bool IsChannelActive(LogChannel channel) { return(ChannelsActiveState[(int)channel]); }
public static void Log(string msg, LogChannel channel) { Log(msg, channel, LogLvl.Info); }
public static void Log(LogChannel channel, string text, bool multi = false) { if (!multi) Write(new LogEntry(text, null) { channel = channel }); else { var split = text.Split('\n'); foreach (var line in split) Write(new LogEntry(line, null) { channel = channel }); } }
public static void LogWarning(string msg, LogChannel channel) { Log(msg, channel, LogLvl.Warning); }
public LogEntry(object message, object args, SendingLogger logger = SendingLogger.CONSOLE) { this.target = null; this.thread = Thread.CurrentThread; this.time = DateTime.Now; this.message = message; this.args = args; this.channel = null; this.logger = logger; }
public static void LogError(string msg, LogChannel channel) { Log(msg, channel, LogLvl.Error); }
public static void BareLog(LogChannel channel, string format, params object[] args) { Write (new LogEntry { message = format, args = args, thread = Thread.CurrentThread, channel = channel }); }
public static void LogAssertion(string msg, LogChannel channel) { Log(msg, channel, LogLvl.Assertion); }
public LogEntry(object message, object args) { this.target = null; this.thread = Thread.CurrentThread; this.time = DateTime.Now; this.message = message; this.args = args; this.channel = null; }
private static void LogFormat(string format, LogChannel channel, LogLvl level, params object[] args) { Log(string.Format(format, args), channel, level); }
public static void Log(LogChannel channel, string format, params object[] args) { Write (new LogEntry (format, args) { channel = channel }); }
public static void LogWarningFormat(string format, LogChannel channel, params object[] args) { LogFormat(format, channel, LogLvl.Warning, args); }
public static void LogErrorFormat(string format, LogChannel channel, params object[] args) { LogFormat(format, channel, LogLvl.Error, args); }
public void Constructor() { LogChannel lc = new LogChannel("Test-Channel"); Assert.IsNotNull(lc); Assert.AreEqual("Test-Channel", lc.Name); }