public void WriteViolation(RuleViolation ruleViolation) { switch (ruleViolation.ViolationType) { case ViolationType.Warning: _log.LogWarning( null, null, null, ruleViolation.Dependency.FileName, (int)ruleViolation.Dependency.StartLine, (int)ruleViolation.Dependency.StartColumn, (int)ruleViolation.Dependency.EndLine, (int)ruleViolation.Dependency.EndColumn, ruleViolation.Dependency.QuestionableMessage()); break; case ViolationType.Error: _log.LogError( null, null, null, ruleViolation.Dependency.FileName, (int)ruleViolation.Dependency.StartLine, (int)ruleViolation.Dependency.StartColumn, (int)ruleViolation.Dependency.EndLine, (int)ruleViolation.Dependency.EndColumn, ruleViolation.Dependency.IllegalMessage()); break; default: throw new ArgumentOutOfRangeException(); } }
/// <summary> /// Reads the specified file from disk into a StateFileBase derived object. /// </summary> /// <param name="stateFile"></param> /// <returns></returns> static internal StateFileBase DeserializeCache(string stateFile, TaskLoggingHelper log, Type requiredReturnType) { StateFileBase retVal = null; // First, we read the cache from disk if one exists, or if one does not exist // then we create one. try { if (stateFile != null && stateFile.Length > 0 && File.Exists(stateFile)) { using (FileStream s = new FileStream(stateFile, FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); retVal = (StateFileBase)formatter.Deserialize(s); if ((retVal != null) && (!requiredReturnType.IsInstanceOfType(retVal))) { log.LogWarning("Could not write state file {0} (Incompatible state file type)", stateFile); retVal = null; } } } } catch (Exception e) { // The deserialization process seems like it can throw just about // any exception imaginable. Catch them all here. // Not being able to deserialize the cache is not an error, but we let the user know anyway. // Don't want to hold up processing just because we couldn't read the file. log.LogWarning("Could not read state file {0} ({1})", stateFile, e.Message); } return(retVal); }
public void LogLinker(string message, ShellAppConversion shellApp, params object[] parameters) { lock (sync) { string pattern = @"(.*?):(?![\\\/])(.*?)"; Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase); MatchCollection matches = rgx.Matches(message); if ((matches.Count >= 1) && (matches[0].Groups.Count > 2)) { GroupCollection groups = matches[0].Groups; string filename = groups[1].Value; if (shellApp != null && shellApp.convertpath) { message = message.Substring(message.IndexOf(filename) + filename.Length + 1); filename = shellApp.ConvertWSLPathToWin(filename); } if (!general_err.Match(message).Success&& (general_warn.Match(message).Success || general_inf.Match(message).Success)) { log.LogWarning(null, null, null, filename, 0, 0, 0, 0, message); } else { log.LogError(null, null, null, filename, 0, 0, 0, 0, message); } } else { log.LogError(message, parameters); } } }
public static IDictionary <string, string> GetNamedProperties(string[] input, TaskLoggingHelper log) { Dictionary <string, string> values = new(StringComparer.OrdinalIgnoreCase); if (input == null) { return(values); } foreach (string item in input) { int splitIdx = item.IndexOf('='); if (splitIdx < 0) { log.LogWarning($"Property: {item} does not have a valid '=' separator"); continue; } string key = item.Substring(0, splitIdx).Trim(); if (string.IsNullOrEmpty(key)) { log.LogWarning($"Property: {item} does not have a valid property name"); continue; } string value = item.Substring(splitIdx + 1); values[key] = value; } return(values); }
private static Dictionary <string, string> ParseSeedTypePreferences(ITaskItem[] preferences, TaskLoggingHelper logger) { var dictionary = new Dictionary <string, string>(StringComparer.Ordinal); if (preferences != null) { foreach (var item in preferences) { string key = item.ItemSpec; string value = item.GetMetadata("Aliases"); if (value != null) { string existingValue; if (dictionary.TryGetValue(key, out existingValue)) { logger.LogWarning($"Overriding SeedType{existingValue} for type {key} with {value}"); } dictionary[key] = value; } else { logger.LogWarning($"No Alias has been provided for type {key}"); } } } return(dictionary); }
public static IEnumerable <int> GetSupportedPlatforms(TaskLoggingHelper log, string androidNdkPath) { string preNdk22PlatformsDir = Path.Combine(androidNdkPath, "platforms"); if (Directory.Exists(preNdk22PlatformsDir)) { return(GetSupportedPlatformsPreNdk22(preNdk22PlatformsDir)); } // NDK r22 no longer has a single platforms dir. The API level directories are now found in per-arch // subdirectories under the toolchain directory. We need to examine all of them and compose a list of unique // API levels (since they are repeated in each per-arch subdirectory, but not all architectures have the // same set of API levels) var apiLevels = new HashSet <int> (); string sysrootLibDir = GetNdk22OrNewerSysrootDir(androidNdkPath); foreach (AndroidTargetArch targetArch in Enum.GetValues(typeof(AndroidTargetArch))) { if (targetArch == AndroidTargetArch.None || targetArch == AndroidTargetArch.Other || targetArch == AndroidTargetArch.Mips) { continue; } string archDirName = GetArchDirName(targetArch); if (String.IsNullOrEmpty(archDirName)) { log.LogWarning($"NDK architecture {targetArch} unknown?"); continue; } string archDir = Path.Combine(sysrootLibDir, archDirName); if (!Directory.Exists(archDir)) { log.LogWarning($"Architecture {targetArch} toolchain directory '{archDir}' not found"); continue; } foreach (string platform in Directory.EnumerateDirectories(archDir, "*", SearchOption.TopDirectoryOnly)) { string plibc = Path.Combine(platform, "libc.so"); if (!File.Exists(plibc)) { continue; } string pdir = Path.GetFileName(platform); int api; if (!Int32.TryParse(pdir, out api) || apiLevels.Contains(api)) { continue; } apiLevels.Add(api); } } return(apiLevels); }
private void CacheDatabase(string cacheDBPath, string[] connectionStrings, string sqlWrapperPath) { if (File.Exists(cacheDBPath)) { return; } using (Process sqlwrapperProcess = new Process()) { string assemblyDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(SQLWrapper)).Location); if (!Directory.Exists(Path.Combine(assemblyDirectory, "tools"))) { // nuget assemblyDirectory = Path.Combine(assemblyDirectory, "..", ".."); } if (string.IsNullOrWhiteSpace(sqlWrapperPath)) { sqlWrapperPath = Path.Combine(assemblyDirectory, "tools", "SQLWrapper.exe"); } sqlwrapperProcess.StartInfo.WorkingDirectory = assemblyDirectory; sqlwrapperProcess.StartInfo.FileName = sqlWrapperPath; sqlwrapperProcess.StartInfo.UseShellExecute = false; sqlwrapperProcess.StartInfo.CreateNoWindow = true; sqlwrapperProcess.StartInfo.RedirectStandardOutput = true; sqlwrapperProcess.StartInfo.RedirectStandardError = true; sqlwrapperProcess.StartInfo.Arguments = "database -t mariadb -c "; foreach (string connectionString in connectionStrings) { sqlwrapperProcess.StartInfo.Arguments += " \"" + connectionString.Replace("\"", "\"\"") + "\" "; } sqlwrapperProcess.StartInfo.Arguments += "-o " + cacheDBPath; sqlwrapperProcess.Start(); // Synchronously read the standard output of the spawned process. StreamReader readerOutput = sqlwrapperProcess.StandardOutput; _log.LogWarning(readerOutput.ReadToEnd()); StreamReader readerError = sqlwrapperProcess.StandardError; string error = readerError.ReadToEnd(); if (!string.IsNullOrWhiteSpace(error)) { _log.LogError(error); } } }
public static bool TryLocatePackagesFolder(TaskLoggingHelper logger, out string executablePath) { executablePath = null; var taskLibPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var dir = new DirectoryInfo(taskLibPath); DirectoryInfo root = null; DirectoryInfo[] subDirs = null; logger.LogMessage("Task lib location: {0}", dir.FullName); if (dir.Parent == null) { logger.LogWarning("Unable to determine parent folder."); return(false); } if (dir.Parent.Parent == null) { logger.LogWarning("Unable to determine root folder."); return(false); } root = dir.Parent.Parent; subDirs = root.GetDirectories("ILMerge.*", SearchOption.TopDirectoryOnly); logger.LogMessage("Package location: {0}", root.FullName); if (subDirs == null || subDirs.Count() == 0) { logger.LogWarning("No folder starting with 'ILMerge' were found under {0}.", root.FullName); return(false); } foreach (var item in subDirs) { var files = item.GetFiles("ILMerge.exe", SearchOption.AllDirectories); if (files != null && files.Any()) { logger.LogMessage("Executable found by dynamic searach at: {0}", item.FullName); executablePath = files[0].FullName; return(true); } } return(false); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Temporarily registers the specified file. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="registerInHklm"><c>true</c> to register in HKLM, <c>false</c> to /// register in HKCU. Passing <c>false</c> has the same effect as calling /// regsvr32 with parameter /i:user.</param> /// <param name="registerTypeLib"><c>true</c> to also register tye type library.</param> /// ------------------------------------------------------------------------------------ public bool Register(string fileName, bool registerInHklm, bool registerTypeLib) { SetDllDirectory(Path.GetDirectoryName(fileName)); ApiInvokeDllInstall(m_Log, fileName, true, registerInHklm); try { if (registerInHklm && registerTypeLib) { ITypeLib typeLib = LoadTypeLib(fileName); var registerResult = RegisterTypeLib(typeLib, fileName, null); if (registerResult == 0) { m_Log.LogMessage(MessageImportance.Low, "Registered {0} with result {1}", fileName, registerResult); } else { m_Log.LogWarning("Registering {0} failed with result {1}", fileName, registerResult); } } else { m_Log.LogMessage(MessageImportance.Low, "Registered {0}", fileName); } } catch (Exception e) { m_Log.LogWarningFromException(e); } return(true); }
public DiagnosticMessageSink(TaskLoggingHelper log, string assemblyDisplayName, bool showDiagnostics) { if (showDiagnostics) { Diagnostics.DiagnosticMessageEvent += args => log.LogWarning("{0}: {1}", assemblyDisplayName, args.Message.Message); } }
/// <summary> /// Log Errors/Warnings/Messages when the compiler reports them. /// </summary> /// <param name="path">Path to the file where the error was found (null/empty if N/A)</param> /// <param name="message">Text of the error/warning/message</param> /// <param name="startLine">First line of the block containing the error (0 if N/A)</param> /// <param name="startColumn">First column of the block containing the error (0 if N/A)</param> /// <param name="endLine">Last line of the block containing the error (0 if N/A)</param> /// <param name="endColumn">Last column of the block containing the error (0 if N/A)</param> /// <param name="errorCode">Code corresponding to the error</param> /// <param name="severity">Error/Warning/Message</param> public override void AddError(string path, string message, string lineText, FoxPro.Hosting.CodeSpan location, int errorCode, FoxPro.Hosting.Severity severity) { if (ProjectDirectory != null && !System.IO.Path.IsPathRooted(path)) { path = System.IO.Path.Combine(ProjectDirectory, path); } // Based on the type of event (error/warning/message), report the corresponding type of problem to MSBuild switch (severity) { case FoxPro.Hosting.Severity.Error: { buildSucceeded = false; taskLogger.LogError(String.Empty, "PY" + errorCode.ToString(), String.Empty, path, location.StartLine, location.StartColumn, location.EndLine, location.EndColumn, message); break; } case FoxPro.Hosting.Severity.Warning: { taskLogger.LogWarning(String.Empty, "PY" + errorCode.ToString(), String.Empty, path, location.StartLine, location.StartColumn, location.EndLine, location.EndColumn, message); break; } case FoxPro.Hosting.Severity.Message: { taskLogger.LogMessage(message); break; } } }
void CreateImportFor(bool isNestedSrc, IEnumerable <TypeDefinition> types, CodeMemberMethod method) { foreach (var type in types) { // If the library was written in F#, those resource ID classes are not nested but rather combined with '_'. var srcClassRef = new CodeTypeReferenceExpression( new CodeTypeReference(primary_name + (isNestedSrc ? '.' : '_') + type.Name, CodeTypeReferenceOptions.GlobalReference)); // destination language may not support nested types, but they should take care of such types by themselves. var dstClassRef = new CodeTypeReferenceExpression( new CodeTypeReference(type.FullName.Replace('/', '.'), CodeTypeReferenceOptions.GlobalReference)); foreach (var field in type.Fields) { var dstField = new CodeFieldReferenceExpression(dstClassRef, field.Name); var srcField = new CodeFieldReferenceExpression(srcClassRef, field.Name); var fieldName = CreateIdentifier(type.Name, field.Name); if (!resourceFields.Contains(fieldName)) { Log.LogWarning(subcategory: null, warningCode: "XA0106", helpKeyword: null, file: null, lineNumber: 0, columnNumber: 0, endLineNumber: 0, endColumnNumber: 0, message: $"Skipping {fieldName}. Please check that your Nuget Package versions are compatible." ); continue; } // This simply assigns field regardless of whether it is int or int[]. method.Statements.Add(new CodeAssignStatement(dstField, srcField)); } } }
public static string GetSteamAppPath(TaskLoggingHelper taskLoggingHelper, uint appId) { try { if (!SteamClient.IsValid) { SteamClient.Init(appId); } } catch (Exception ex) { taskLoggingHelper.LogWarning(ex.ToString()); #if DEBUG Debugger.Launch(); #endif } string path = null; try { path = SteamApps.AppInstallDir(appId); } catch (Exception ex) { taskLoggingHelper.LogError(ex.ToString()); #if DEBUG Debugger.Launch(); #endif } return(path); }
public override void WriteLine(string outputText, BuildLoggerLevel level) { if (level == BuildLoggerLevel.None) { return; } if (level == BuildLoggerLevel.Started) { _logHelper.LogMessage(this.FormatText(outputText, level)); } else if (level == BuildLoggerLevel.Ended) { _logHelper.LogMessage(this.FormatText(outputText, level)); } else if (level == BuildLoggerLevel.Warn) { _warningCount++; _logHelper.LogWarning(null, _warningCount.ToString(), String.Empty, this.PrefixWarn, 0, 0, 0, 0, outputText); } else if (level == BuildLoggerLevel.Error) { _errorCount++; _logHelper.LogError(null, _errorCount.ToString(), String.Empty, this.PrefixError, 0, 0, 0, 0, outputText); } else { _logHelper.LogMessage(outputText); } }
/// <summary> /// Writes the contents of this object out to the specified file. /// </summary> /// <param name="stateFile"></param> virtual internal void SerializeCache(string stateFile, TaskLoggingHelper log) { try { if (stateFile != null && stateFile.Length > 0) { if (File.Exists(stateFile)) { File.Delete(stateFile); } using (FileStream s = new FileStream(stateFile, FileMode.CreateNew)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(s, this); } } } catch (Exception e) { // If there was a problem writing the file (like it's read-only or locked on disk, for // example), then eat the exception and log a warning. Otherwise, rethrow. ExceptionHandling.RethrowUnlessFileIO(e); // Not being able to serialize the cache is not an error, but we let the user know anyway. // Don't want to hold up processing just because we couldn't read the file. log.LogWarning("Could not write state file {0} ({1})", stateFile, e.Message); } }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var message = formatter(state, exception); switch (logLevel) { case LogLevel.Critical: _log.LogCriticalMessage(null, null, null, null, 0, 0, 0, 0, message); break; case LogLevel.Error: _log.LogError(message); break; case LogLevel.Warning: _log.LogWarning(message); break; case LogLevel.Information: _log.LogMessage(MessageImportance.High, message); break; case LogLevel.Debug: _log.LogMessage(MessageImportance.Normal, message); break; case LogLevel.Trace: _log.LogMessage(MessageImportance.Low, message); break; } }
private static Assembly AssemblyResolve(object sender, ResolveEventArgs args) { var name = new AssemblyName(args.Name); if (!name.Name.Equals("System.Collections.Immutable", StringComparison.OrdinalIgnoreCase)) { return(null); } var fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System.Collections.Immutable.dll"); Assembly sci; try { sci = Assembly.LoadFile(fullPath); } catch (Exception e) { Log?.LogWarning($"AssemblyResolve: exception while loading '{fullPath}': {e.Message}"); return(null); } if (name.Version <= sci.GetName().Version) { Log?.LogMessage(MessageImportance.Low, $"AssemblyResolve: loaded '{fullPath}' to {AppDomain.CurrentDomain.FriendlyName}"); return(sci); } return(null); }
public static void FixItemSpecs(TaskLoggingHelper log, Func <ITaskItem, string> itemPathFactory, params ITaskItem [] items) { foreach (var item in items) { var targetPath = Path.Combine(itemPathFactory(item), Path.GetFileName(item.ItemSpec)); if (!Directory.Exists(Path.GetDirectoryName(targetPath))) { Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); } // HACK: If the target path is a network directory, GetLastWriteTimeUtc returns some a difference of some milliseconds // for the same file. So we just use Year/Month/Day/Hour/Minute/Second to decide if we should copy the item to the target location. var sourceLastWrite = File.GetLastWriteTimeUtc(item.ItemSpec); var sourceLastWriteFixed = new DateTime(sourceLastWrite.Year, sourceLastWrite.Month, sourceLastWrite.Day, sourceLastWrite.Hour, sourceLastWrite.Minute, sourceLastWrite.Second); var targetLastWrite = File.GetLastWriteTimeUtc(targetPath); var targetLastWriteFixed = new DateTime(targetLastWrite.Year, targetLastWrite.Month, targetLastWrite.Day, targetLastWrite.Hour, targetLastWrite.Minute, targetLastWrite.Second); if (!File.Exists(targetPath) || sourceLastWriteFixed > targetLastWriteFixed) { try { File.Copy(item.ItemSpec, targetPath, true); } catch (Exception ex) { log.LogWarning(ex.Message); } } item.ItemSpec = targetPath; } }
protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData) { if (exceptionData != null) { message += "\n" + exceptionData; } switch (severity) { case LogSeverity.Error: taskLoggingHelper.LogError(message); break; case LogSeverity.Warning: taskLoggingHelper.LogWarning(message); break; case LogSeverity.Important: taskLoggingHelper.LogMessage(MessageImportance.High, message); break; case LogSeverity.Info: taskLoggingHelper.LogMessage(MessageImportance.Normal, message); break; case LogSeverity.Debug: taskLoggingHelper.LogMessage(MessageImportance.Low, message); break; } }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { switch (loggingEvent.Level.Name.ToLower()) { case "alert": case "critical": case "emergency": case "error": case "fatal": case "severe": _taskLoggingHelper.LogError(loggingEvent.RenderedMessage); break; case "warn": _taskLoggingHelper.LogWarning(loggingEvent.RenderedMessage); break; case "info": case "notice": _taskLoggingHelper.LogMessage(MessageImportance.Normal, loggingEvent.RenderedMessage); break; case "debug": case "fine": case "finer": case "finest": case "trace": case "verbose": default: _taskLoggingHelper.LogMessage(MessageImportance.Low, loggingEvent.RenderedMessage); break; } }
/// <summary> /// Log using basic methods to avoid missing methods on mono. /// </summary> private void LogForMono(ILogMessage message) { switch (message.Level) { case LogLevel.Error: _taskLogging.LogError(message.Message); break; case LogLevel.Warning: _taskLogging.LogWarning(message.Message); break; case LogLevel.Minimal: _taskLogging.LogMessage(MessageImportance.High, message.Message); break; case LogLevel.Information: _taskLogging.LogMessage(MessageImportance.Normal, message.Message); break; case LogLevel.Debug: case LogLevel.Verbose: default: // Default to LogLevel.Debug and low importance _taskLogging.LogMessage(MessageImportance.Low, message.Message); break; } return; }
public override void Log(LogLevel logLevel, LogLocation logLocation, string context, string message, Exception exception, params object[] parameters) { if (message == null) { return; } switch (logLevel) { case LogLevel.Info: log.LogMessage(context, null, null, logLocation.File, logLocation.Line, logLocation.Column, 0, 0, Microsoft.Build.Framework.MessageImportance.Normal, message, parameters); break; case LogLevel.Warning: log.LogWarning(context, null, null, logLocation.File, logLocation.Line, logLocation.Column, 0, 0, message, parameters); if (exception != null) { log.LogWarningFromException(exception); } break; case LogLevel.Error: case LogLevel.Fatal: log.LogError(context, null, null, logLocation.File, logLocation.Line, logLocation.Column, 0, 0, message, parameters); if (exception != null) { log.LogErrorFromException(exception, true, true, null); } break; default: break; } }
void ILogger.Write(ILogger.Severity severity, string msg) { var msgImportance = severity switch { ILogger.Severity.Message => MessageImportance.High, ILogger.Severity.Diag => MessageImportance.Low, _ => MessageImportance.Normal }; if (severity == ILogger.Severity.Error) { logger.LogError(msg); } else { logger.LogMessage(msgImportance, msg); } } void ILogger.Warn(string code, string file, int line, int column, string msg) { if (noWarning.Contains(code)) { logger.LogMessage(MessageImportance.Normal, "Suppressed warning " + code + ": " + msg); } else { logger.LogWarning(nameof(InheritDocTask), code, null, file, line, column, 0, 0, msg); } } }
// Calculate part of proto path relative to root. Protoc is very picky // about them matching exactly, so can be we. Expect root be exact prefix // to proto, minus some slash normalization. protected static string GetRelativeDir(string root, string proto, TaskLoggingHelper log) { string protoDir = Path.GetDirectoryName(proto); string rootDir = EndWithSlash(Path.GetDirectoryName(EndWithSlash(root))); if (rootDir == s_dotSlash) { // Special case, otherwise we can return "./" instead of "" below! return(protoDir); } if (Platform.IsFsCaseInsensitive) { protoDir = protoDir.ToLowerInvariant(); rootDir = rootDir.ToLowerInvariant(); } protoDir = EndWithSlash(protoDir); if (!protoDir.StartsWith(rootDir)) { log.LogWarning("Protobuf item '{0}' has the ProtoRoot metadata '{1}' " + "which is not prefix to its path. Cannot compute relative path.", proto, root); return(""); } return(protoDir.Substring(rootDir.Length)); }
public static void InitializeAndroidLogger(TaskLoggingHelper log) { AndroidLogger.Error += (task, message) => log.LogError(task + " " + message); AndroidLogger.Warning += (task, message) => log.LogWarning(task + " " + message); AndroidLogger.Info += (task, message) => log.LogMessage(task + " " + message); AndroidLogger.Debug += (task, message) => log.LogDebugMessage(task + " " + message); }
private void WriteLogEntry(LogLevel level, string str) { var contents = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\t\t{str}{System.Environment.NewLine}"; switch (level) { case LogLevel.Fatal: case LogLevel.Error: taskLog.LogError(contents); break; case LogLevel.Warn: taskLog.LogWarning(contents); break; case LogLevel.Info: case LogLevel.Verbose: case LogLevel.Debug: taskLog.LogMessage(contents); break; default: throw new ArgumentOutOfRangeException(nameof(level), level, null); } }
public static void LogFromStandardError(this TaskLoggingHelper log, string message) { if (string.IsNullOrEmpty(message)) { return; } var m = Message.Match(message); if (!m.Success) { return; } string subcategory = m.Groups ["source"].Value; string type = m.Groups ["type"].Value; string code = m.Groups ["code"].Value; string msg = m.Groups ["message"].Value; if (type == "warning") { log.LogWarning(subcategory, code, string.Empty, string.Empty, 0, 0, 0, 0, "{0}", msg); } else { log.LogError(subcategory, code, string.Empty, string.Empty, 0, 0, 0, 0, "{0}", msg); } }
public static void LogRustcMessage(RustcParsedMessage msg, TaskLoggingHelper log) { Debug.WriteLine(msg.ToString()); if (msg.Type == RustcParsedMessageType.Warning) { log.LogWarning(null, msg.ErrorCode, null, msg.File, msg.LineNumber, msg.ColumnNumber, msg.EndLineNumber, msg.EndColumnNumber, msg.Message); } else if (msg.Type == RustcParsedMessageType.Note) { log.LogWarning(null, msg.ErrorCode, null, msg.File, msg.LineNumber, msg.ColumnNumber, msg.EndLineNumber, msg.EndColumnNumber, "note: " + msg.Message); } else { log.LogError(null, msg.ErrorCode, null, msg.File, msg.LineNumber, msg.ColumnNumber, msg.EndLineNumber, msg.EndColumnNumber, msg.Message); } }
private void StartProcess(string sqlWrapperPath, string arguments, string logCategory, string logFile) { using Process sqlwrapperProcess = new Process(); string assemblyDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(SQLWrapperExecute)).Location); if (!Directory.Exists(Path.Combine(assemblyDirectory, "tools"))) { // nuget assemblyDirectory = Path.Combine(assemblyDirectory, "..", ".."); } if (string.IsNullOrWhiteSpace(sqlWrapperPath)) { sqlWrapperPath = Path.Combine(assemblyDirectory, "tools", "SQLWrapper.exe"); } sqlwrapperProcess.StartInfo.WorkingDirectory = assemblyDirectory; sqlwrapperProcess.StartInfo.FileName = sqlWrapperPath; sqlwrapperProcess.StartInfo.UseShellExecute = false; sqlwrapperProcess.StartInfo.CreateNoWindow = true; sqlwrapperProcess.StartInfo.RedirectStandardOutput = true; sqlwrapperProcess.StartInfo.RedirectStandardError = true; sqlwrapperProcess.StartInfo.Arguments = arguments; sqlwrapperProcess.Start(); // Synchronously read the standard output of the spawned process. StreamReader readerOutput = sqlwrapperProcess.StandardOutput; string error = readerOutput.ReadToEnd(); if (!string.IsNullOrWhiteSpace(error)) { _log.LogWarning(logCategory, "", "", logFile, 0, 0, 0, 0, error, null); } StreamReader readerError = sqlwrapperProcess.StandardError; error = readerError.ReadToEnd(); if (!string.IsNullOrWhiteSpace(error)) { int lineNumber = 0; int columnNumber = 0; string code = ""; Match match = Regex.Match(error, @"(?<filepath>.*):\((?<line>.*),(?<position>\d+)\):(?<code>[^:]*):(?<message>.*)"); if (match.Success) { logFile = match.Groups["filepath"].Value; lineNumber = int.Parse(match.Groups["line"].Value, CultureInfo.InvariantCulture); columnNumber = int.Parse(match.Groups["position"].Value, CultureInfo.InvariantCulture); code = match.Groups["code"].Value.TrimStart(); error = match.Groups["message"].Value.TrimStart(); } _log.LogError(logCategory, code, "", logFile, lineNumber, columnNumber, 0, 0, error, null); } sqlwrapperProcess.WaitForExit(); }
protected override void Write(Levels level, DContext context, string url, int column, int lineNr, string msg, Exception exception, object[] args) { if (level < Levels.Info) { return; } if ((msg == null) && (exception != null)) { msg = exception.Message; } if (msg == null) { return; } lineNr = Math.Max(0, lineNr); column = Math.Max(0, column); switch (level) { //case Levels.Info: // log.LogMessage(msg, args); // break; case Levels.Info: //TODO: get LogMessage to work. case Levels.Warning: if (url != null) { log.LogWarning(null, null, null, url, lineNr, column, 0, 0, msg, args); } else { log.LogWarning(msg, args); } break; case Levels.Error: if (url != null) { log.LogError(null, null, null, url, lineNr, column, 0, 0, msg, args); } else { log.LogError(msg, args); } break; } }