当前位置: 首页>>代码示例>>C#>>正文


C# ILogger.LogError方法代码示例

本文整理汇总了C#中ILogger.LogError方法的典型用法代码示例。如果您正苦于以下问题:C# ILogger.LogError方法的具体用法?C# ILogger.LogError怎么用?C# ILogger.LogError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ILogger的用法示例。


在下文中一共展示了ILogger.LogError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: RemoteConfigManager

 public RemoteConfigManager(IResourceLoader loader, IStorage storage, ILogger logger, RuntimePlatform platform)
 {
     this.storage = storage;
     logger.prefix = "Unibill.RemoteConfigManager";
     this.XML = loader.openTextFile ("unibillInventory.json").ReadToEnd ();
     Config = new UnibillConfiguration(XML, platform, logger);
     if (Config.UseHostedConfig) {
         string val = storage.GetString (CACHED_CONFIG_PATH, string.Empty);
         if (string.IsNullOrEmpty (val)) {
             logger.Log ("No cached config available. Using bundled");
         } else {
             logger.Log ("Cached config found, attempting to parse");
             try {
                 Config = new UnibillConfiguration(val, platform, logger);
                 if (Config.inventory.Count == 0) {
                     logger.LogError ("No purchasable items in cached config, ignoring.");
                     Config = new UnibillConfiguration (XML, platform, logger);
                 } else {
                     logger.Log (string.Format ("Using cached config with {0} purchasable items", Config.inventory.Count));
                     XML = val;
                 }
             } catch (Exception e) {
                 logger.LogError ("Error parsing inventory: {0}", e.Message);
                 Config = new UnibillConfiguration(XML, platform, logger);
             }
         }
         refreshCachedConfig (Config.HostedConfigUrl, logger);
     } else {
         logger.Log ("Not using cached inventory, using bundled.");
         Config = new UnibillConfiguration(XML, platform, logger);
     }
 }
开发者ID:jhillkwaj,项目名称:WordsOnWords,代码行数:32,代码来源:RemoteConfigManager.cs

示例2: SafeCloseClientSocket

        public static void SafeCloseClientSocket(this Socket client, ILogger logger)
        {
            if(client == null)
                return;

            if (!client.Connected)
                return;
            
            try
            {
                client.Shutdown(SocketShutdown.Both);
            }
            catch(ObjectDisposedException)
            {
            }
            catch(Exception e)
            {
                if(logger != null)
                    logger.LogError(e);
            }
            
            try
            {
                client.Close();
            }
            catch(ObjectDisposedException)
            {
            }
            catch(Exception e)
            {
                if(logger != null)
                    logger.LogError(e);
            }
        }
开发者ID:xxjeng,项目名称:nuxleus,代码行数:34,代码来源:SocketEx.cs

示例3: GenerateFile

        public /* for test */ static ProjectInfoAnalysisResult GenerateFile(AnalysisConfig config, ILogger logger, IRoslynV1SarifFixer fixer)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string fileName = Path.Combine(config.SonarOutputDir, ProjectPropertiesFileName);
            logger.LogDebug(Resources.MSG_GeneratingProjectProperties, fileName);

            IEnumerable<ProjectInfo> projects = ProjectLoader.LoadFrom(config.SonarOutputDir);
            if (projects == null || !projects.Any())
            {
                logger.LogError(Resources.ERR_NoProjectInfoFilesFound);
                return new ProjectInfoAnalysisResult();
            }

            FixSarifReport(logger, projects, fixer);

            PropertiesWriter writer = new PropertiesWriter(config);

            ProjectInfoAnalysisResult result = ProcessProjectInfoFiles(projects, writer, logger);

            IEnumerable<ProjectInfo> validProjects = result.GetProjectsByStatus(ProjectInfoValidity.Valid);

            if (validProjects.Any())
            {
                // Handle global settings
                AnalysisProperties properties = GetAnalysisPropertiesToWrite(config, logger);
                writer.WriteGlobalSettings(properties);

                string contents = writer.Flush();

                result.FullPropertiesFilePath = fileName;
                File.WriteAllText(result.FullPropertiesFilePath, contents, Encoding.ASCII);
            }
            else
            {
                // if the user tries to build multiple configurations at once there will be duplicate projects
                if (result.GetProjectsByStatus(ProjectInfoValidity.DuplicateGuid).Any())
                {
                    logger.LogError(Resources.ERR_NoValidButDuplicateProjects);
                }
                else
                {
                    logger.LogError(Resources.ERR_NoValidProjectInfoFiles);
                }
            }
            return result;
        }
开发者ID:BrightLight,项目名称:sonar-msbuild-runner,代码行数:54,代码来源:PropertiesFileGenerator.cs

示例4: TryGetConfig

        public const int DelayBetweenRetriesInMilliseconds = 499; // Period to wait between retries

        #region Public methods

        /// <summary>
        /// Attempts to load the analysis config from the specified directory.
        /// Will retry if the file is locked.
        /// </summary>
        /// <returns>The loaded configuration, or null if the file does not exist or could not be
        /// loaded e.g. due to being locked</returns>
        public static AnalysisConfig TryGetConfig(string configDir, ILogger logger)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            AnalysisConfig config = null;
            if (string.IsNullOrEmpty(configDir)) // not specified
            {
                return null;
            }

            string fullAnalysisPath = Path.Combine(configDir, FileConstants.ConfigFileName);
            logger.LogDebug(Resources.Shared_ReadingConfigFile, fullAnalysisPath);
            if (!File.Exists(fullAnalysisPath))
            {
                logger.LogDebug(Resources.Shared_ConfigFileNotFound);
                return null;
            }

            bool succeeded = Utilities.Retry(MaxConfigRetryPeriodInMilliseconds, DelayBetweenRetriesInMilliseconds, logger,
                () => DoLoadConfig(fullAnalysisPath, logger, out config));
            if (succeeded)
            {
                logger.LogDebug(Resources.Shared_ReadingConfigSucceeded, fullAnalysisPath);
            }
            else
            {
                logger.LogError(Resources.Shared_ReadingConfigFailed, fullAnalysisPath);
            }
            return config;
        }
开发者ID:BrightLight,项目名称:sonar-msbuild-runner,代码行数:43,代码来源:TaskUtilities.cs

示例5: HandleHostUrlWebException

        /// <summary>
        /// Common logic for handling web exceptions when connecting to the SonarQube server. Common exceptions 
        /// are handled by logging user friendly errors.
        /// </summary>
        /// <returns>True if the exception was handled</returns>
        public static bool HandleHostUrlWebException(WebException ex, string hostUrl, ILogger logger)
        {
            var response = ex.Response as HttpWebResponse;
            if (response != null && response.StatusCode == HttpStatusCode.NotFound)
            {
                logger.LogError(Resources.ERROR_FileNotFound, response.ResponseUri);
                return true;
            }

            if (ex.Status == WebExceptionStatus.NameResolutionFailure)
            {
                logger.LogError(Resources.ERROR_UrlNameResolutionFailed, hostUrl);
                return true;
            }

            if (ex.Status == WebExceptionStatus.ConnectFailure)
            {
                logger.LogError(Resources.ERROR_ConnectionFailed, hostUrl);
                return true;
            }

            if (ex.Status == WebExceptionStatus.TrustFailure)
            {
                logger.LogError(Resources.ERROR_TrustFailure, hostUrl);
                return true;
            }

            return false;
        }
开发者ID:pascalberger,项目名称:sonar-msbuild-runner,代码行数:34,代码来源:Utilities.cs

示例6: Execute

        public ProjectInfoAnalysisResult Execute(AnalysisConfig config, IEnumerable<string> userCmdLineArguments, ILogger logger)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (userCmdLineArguments == null)
            {
                throw new ArgumentNullException("userCmdLineArguments");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger);
            Debug.Assert(result != null, "Not expecting the file generator to return null");
            result.RanToCompletion = false;

            SonarProjectPropertiesValidator.Validate(
                config.SonarRunnerWorkingDirectory,
                result.Projects,
                onValid: () =>
                {
                    InternalExecute(config, userCmdLineArguments, logger, result);
                },
                onInvalid: (invalidFolders) =>
                {
                    // LOG error message
                    logger.LogError(Resources.ERR_ConflictingSonarProjectProperties, string.Join(", ", invalidFolders));
                });

            return result;
        }
开发者ID:BrightLight,项目名称:sonar-msbuild-runner,代码行数:34,代码来源:SonarRunner.Wrapper.cs

示例7: Route

 public static void Route(ILogger logger, string msg)
 {
     if (!msg.IsNullOrEmpty())
     {
         if (msg.StartsWith(StartVerbose))
             _isVerboseMode = true;
         else if (msg.StartsWith(StopVerbose))
             _isVerboseMode = false;
         else
         {
             if (msg.StartsWith(Verbose))
                 logger.LogVerbose(msg.Substring(Verbose.Length));
             else if (msg.StartsWith(Success))
                 logger.LogSuccess(msg.Substring(Success.Length));
             else if (msg.StartsWith(Warning))
                 logger.LogWarning(msg.Substring(Warning.Length));
             else if (msg.StartsWith(Error))
                 logger.LogError(msg.Substring(Error.Length));
             else if (msg.StartsWith(Header))
             {
                 _isVerboseMode = false;
                 logger.LogHeader(msg.Substring(Header.Length));
             }
             else if (_isVerboseMode)
                 logger.LogVerbose(msg);
             else
                 logger.LogInfo(msg);
         }
     }
     else
     {
         //logger.LogInfo(msg);
     }
 }
开发者ID:mdavid626,项目名称:triton,代码行数:34,代码来源:LogRouter.cs

示例8: Main

        public static void Main(string[] args) {
            var configBuilder = new ConfigurationBuilder().AddCommandLine(args);
            Configuration = configBuilder.Build();

            string configFile = Configuration["config"];
            if (configFile != null) {
                configBuilder.AddJsonFile(configFile, optional: false);
                Configuration = configBuilder.Build();
            }

            ConfigurationBinder.Bind(Configuration.GetSection("startup"), _startupOptions);
            ConfigurationBinder.Bind(Configuration.GetSection("security"), _securityOptions);

            _loggerFactory
                .AddDebug()
                .AddConsole(LogLevel.Trace)
                .AddProvider(new FileLoggerProvider(_startupOptions.Name));
            _logger = _loggerFactory.CreateLogger<Program>();

            if (_startupOptions.Name != null) {
                _logger.LogInformation(Resources.Info_BrokerName, _startupOptions.Name);
            }

            var tlsConfig = new TlsConfiguration(_logger, _securityOptions);
            var httpsOptions = tlsConfig.GetHttpsOptions(Configuration);

            Uri uri = GetServerUri(Configuration);
            try {
                CreateWebHost(httpsOptions).Run();
            } catch(AggregateException ex) when (ex.IsPortInUseException()) {
                _logger.LogError(0, ex.InnerException, Resources.Error_ConfiguredPortNotAvailable, uri?.Port);
            }
        }
开发者ID:Microsoft,项目名称:RTVS,代码行数:33,代码来源:Program.cs

示例9: QueuedItemFromSensorDataContract

        public static QueuedItem QueuedItemFromSensorDataContract( SensorDataContract sensorData, ILogger logger = null )
        {
            if( sensorData == null )
            {
                return null;
            }

            QueuedItem result = null;
            try
            {
                result = new QueuedItem
                {
                    JsonData = JsonConvert.SerializeObject( sensorData )
                };
            }
            catch( Exception ex )
            {
                if( logger != null )
                {
                    logger.LogError( "Error on serialize item: " + ex.Message );
                }
            }

            return result;
        }
开发者ID:dxcamps,项目名称:connectthedots,代码行数:25,代码来源:QueuedItem.cs

示例10: PreProcess

        private static int PreProcess(IBuildAgentUpdater updater, IBootstrapperSettings settings, ILogger logger)
        {
            string downloadBinPath = settings.DownloadDirectory;

            logger.LogInfo(Resources.MSG_PreparingDirectories);
            if (!Utilities.TryEnsureEmptyDirectories(logger,
                settings.TempDirectory,
                downloadBinPath))
            {
                return ErrorCode;
            }

            string server = settings.SonarQubeUrl;
            Debug.Assert(!string.IsNullOrWhiteSpace(server), "Not expecting the server url to be null/empty");
            logger.LogDebug(Resources.MSG_ServerUrl, server);

            logger.LogInfo(Resources.MSG_CheckingForUpdates);
            if (!updater.TryUpdate(server, downloadBinPath, logger))
            {
                logger.LogError(Resources.ERROR_FailedToUpdateRunnerBinaries);
                return ErrorCode;
            }

            if (!updater.CheckBootstrapperApiVersion(settings.SupportedBootstrapperVersionsFilePath, settings.BootstrapperVersion))
            {
                logger.LogError(Resources.ERROR_VersionMismatch);
                return ErrorCode;
            }

            var preprocessorFilePath = settings.PreProcessorFilePath;

            ProcessRunnerArguments runnerArgs = new ProcessRunnerArguments(preprocessorFilePath, logger)
            {
                CmdLineArgs = settings.ChildCmdLineArgs,
                WorkingDirectory = settings.TempDirectory,
            };
            ProcessRunner runner = new ProcessRunner();
            runner.Execute(runnerArgs);

            return runner.ExitCode;
        }
开发者ID:BrightLight,项目名称:sonar-msbuild-runner,代码行数:41,代码来源:Program.cs

示例11: LogProcessingCompleted

 private static void LogProcessingCompleted(AnalysisPhase phase, int exitCode, ILogger logger)
 {
     string phaseLabel = phase == AnalysisPhase.PreProcessing ? Resources.PhaseLabel_PreProcessing : Resources.PhaseLabel_PostProcessing;
     if (exitCode == ProcessRunner.ErrorCode)
     {
         logger.LogError(Resources.ERROR_ProcessingFailed, phaseLabel, exitCode);
     }
     else
     {
         logger.LogInfo(Resources.MSG_ProcessingSucceeded, phaseLabel);
     }
 }
开发者ID:nilleb,项目名称:sonar-msbuild-runner,代码行数:12,代码来源:Program.cs

示例12: RetryRequest

        /// <summary>
        /// Retries every 1 sec for 60 times by default.
        /// </summary>
        /// <param name="retryBlock"></param>
        /// <param name="logger"></param>
        /// <param name="cancellationToken"></param>
        /// <param name="retryCount"></param>
        public static async Task<HttpResponseMessage> RetryRequest(
            Func<Task<HttpResponseMessage>> retryBlock,
            ILogger logger,
            CancellationToken cancellationToken = default(CancellationToken),
            int retryCount = 60)
        {
            for (int retry = 0; retry < retryCount; retry++)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    logger.LogInformation("Failed to connect, retry canceled.");
                    throw new OperationCanceledException("Failed to connect, retry canceled.", cancellationToken);
                }

                try
                {
                    logger.LogWarning("Retry count {retryCount}..", retry + 1);
                    var response = await retryBlock();

                    if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        // Automatically retry on 503. May be application is still booting.
                        logger.LogWarning("Retrying a service unavailable error.");
                        continue;
                    }

                    return response; // Went through successfully
                }
                catch (Exception exception)
                {
                    if (retry == retryCount - 1)
                    {
                        logger.LogError("Failed to connect, retry limit exceeded.", exception);
                        throw;
                    }
                    else
                    {
                        if (exception is HttpRequestException
#if DNX451
                        || exception is System.Net.WebException
#endif
                        )
                        {
                            logger.LogWarning("Failed to complete the request : {0}.", exception.Message);
                            await Task.Delay(1 * 1000); //Wait for a while before retry.
                        }
                    }
                }
            }

            logger.LogInformation("Failed to connect, retry limit exceeded.");
            throw new OperationCanceledException("Failed to connect, retry limit exceeded.");
        }
开发者ID:qiudesong,项目名称:Hosting,代码行数:60,代码来源:RetryHelper.cs

示例13: TryGetBinaryReportFile

        protected override bool TryGetBinaryReportFile(AnalysisConfig config, TeamBuildSettings settings, ILogger logger, out string binaryFilePath)
        {
            IEnumerable<string> urls = this.urlProvider.GetCodeCoverageReportUrls(config.GetTfsUri(), config.GetBuildUri(), logger);
            Debug.Assert(urls != null, "Not expecting the returned list of urls to be null");

            bool continueProcessing = true;
            binaryFilePath = null;

            switch (urls.Count())
            {
                case 0:
                    logger.LogInfo(Resources.PROC_DIAG_NoCodeCoverageReportsFound);
                    break;

                case 1:
                    string url = urls.First();

                    string targetFileName = Path.Combine(config.SonarOutputDir, DownloadFileName);
                    bool result = this.downloader.DownloadReport(config.GetTfsUri(), url, targetFileName, logger);

                    if (result)
                    {
                        binaryFilePath = targetFileName;
                    }
                    else
                    {
                        continueProcessing = false;
                        logger.LogError(Resources.PROC_ERROR_FailedToDownloadReport);
                    }
                    break;

                default: // More than one
                    continueProcessing = false;
                    logger.LogError(Resources.PROC_ERROR_MultipleCodeCoverageReportsFound);
                    break;
            }

            return continueProcessing;
        }
开发者ID:BrightLight,项目名称:sonar-msbuild-runner,代码行数:39,代码来源:TfsLegacyCoverageReportProcessor.cs

示例14: Compile

        public static MemoryStream Compile(string assemblyName, AssemblyInfo assemblyInfo, IEnumerable<SyntaxTree> trees, IEnumerable<MetadataReference> references, ILogger logger = null)
        {
            trees = trees.Concat(new[] { GetAssemblyInfo(assemblyInfo) });
            var compilation = CSharpCompilation.Create(assemblyName, trees, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            var stream = new MemoryStream();
            var result = compilation.Emit(stream);
            if (!result.Success && logger != null)
            {
                foreach (var message in result.Diagnostics.Select(i => i.ToString()))
                {
                    logger.LogError(message);
                }
                return null;
            }
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }
开发者ID:RabbitTeam,项目名称:Rpc,代码行数:18,代码来源:CompilationUtilitys.cs

示例15: TryUpdate

        /// <summary>
        /// Gets a zip file containing the pre/post processors from the server
        /// </summary>
        /// <param name="hostUrl">The server Url</param>
        public bool TryUpdate(string hostUrl, string targetDir, ILogger logger)
        {
            if (string.IsNullOrWhiteSpace(hostUrl))
            {
                throw new ArgumentNullException("hostUrl");
            }
            if (string.IsNullOrWhiteSpace(targetDir))
            {
                throw new ArgumentNullException("targetDir");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string integrationUrl = GetDownloadZipUrl(hostUrl);
            string downloadedZipFilePath = Path.Combine(targetDir, BootstrapperSettings.SonarQubeIntegrationFilename);

            // SONARMSBRU-169 Support TLS versions 1.0, 1.1 and 1.2
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            using (WebClient client = new WebClient())
            {
                try
                {
                    logger.LogDebug(Resources.MSG_DownloadingZip, BootstrapperSettings.SonarQubeIntegrationFilename, integrationUrl, downloadedZipFilePath);
                    client.DownloadFile(integrationUrl, downloadedZipFilePath);
                }
                catch (WebException ex)
                {
                    if (Utilities.HandleHostUrlWebException(ex, hostUrl, logger))
                    {
                        return false;
                    }
                    logger.LogError(Resources.ERROR_FailedToUpdateRunnerBinaries, ex);
                    return false;
                }

                logger.LogDebug(Resources.MSG_ExtractingFiles, targetDir);
                ZipFile.ExtractToDirectory(downloadedZipFilePath, targetDir);
                return true;
            }
        }
开发者ID:Rinorragi,项目名称:sonar-msbuild-runner,代码行数:47,代码来源:BuildAgentUpdater.cs


注:本文中的ILogger.LogError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。