本文整理汇总了C#中ILogger.Error方法的典型用法代码示例。如果您正苦于以下问题:C# ILogger.Error方法的具体用法?C# ILogger.Error怎么用?C# ILogger.Error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ILogger
的用法示例。
在下文中一共展示了ILogger.Error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Upgrade
public override bool Upgrade(PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage, IList<PackageLoadingAssetFile> assetFiles)
{
// Paradox 1.1 projects didn't have their dependency properly updated (they might have been marked as 1.0).
// We know they are 1.1 only because there is a .props file.
// This check shouldn't be necessary from 1.2.
var packagePath = dependentPackage.FullPath;
var propsFilePath = UPath.Combine(packagePath.GetParent(), (UFile)(packagePath.GetFileName() + ".props"));
if (!File.Exists(propsFilePath) && dependency.Version.MinVersion < new PackageVersion("1.1.0-beta"))
{
log.Error("Can't upgrade old projects from {0} 1.0 to 1.1", dependency.Name);
return false;
}
// Nothing to do for now, most of the work is already done by individual asset upgraders
// We can later add logic here for package-wide upgrades (i.e. GameSettingsAsset)
if (dependency.Version.MinVersion < new PackageVersion("1.2.0-beta"))
{
// UIImageGroups and SpriteGroups asset have been merged into a single SpriteSheet => rename the assets and modify the tag
var uiImageGroups = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".pdxuiimage");
var spitesGroups = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".pdxsprite");
RenameAndChangeTag(assetFiles, uiImageGroups, "!UIImageGroup");
RenameAndChangeTag(assetFiles, spitesGroups, "!SpriteGroup");
}
return true;
}
示例2: Process
public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory)
{
// BIG TODO: reengineer command parsing
var componentNamePattern = args.LastOrDefault();
if (componentNamePattern == null || componentNamePattern.StartsWith("-") || componentNamePattern.EndsWith("\"")) {
logger.Error("No component pattern specified");
return true;
}
string tags = args.ParseStringParameter("tags");
string licenseUrl = args.ParseStringParameter("licenseUrl");
string projectUrl = args.ParseStringParameter("projectUrl");
string iconUrl = args.ParseStringParameter("iconUrl");
string copyright = args.ParseStringParameter("copyright");
bool requireLicenseAcceptance = args.Contains("-r");
if (licenseUrl == null && requireLicenseAcceptance) {
logger.Error("Requiring license acceptance demands a license url");
return true;
}
var specificComponent = components.FindComponent<IProject>(componentNamePattern, c => c.CanBecomeNugget);
if (specificComponent == null)
return true;
if (specificComponent.PromoteToNuget(logger, packagesOutputDirectory, tags,
licenseUrl, projectUrl, iconUrl, copyright, requireLicenseAcceptance) != null)
ScanCommand.Rescan(logger, metaProject, components);
return true;
}
示例3: Read
public ReaderResult Read(string resource, ILogger logger) {
var result = new ReaderResult { Source = Source.Url };
try {
var uri = new Uri(resource);
if (!string.IsNullOrEmpty(uri.Query)) {
result.Parameters = HttpUtility.ParseQueryString(uri.Query.Substring(1));
}
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
using (var response = (HttpWebResponse)request.GetResponse()) {
using (var responseStream = response.GetResponseStream()) {
if (responseStream == null) {
} else {
if (response.StatusCode == HttpStatusCode.OK) {
var reader = new StreamReader(responseStream);
result.Content = reader.ReadToEnd();
} else {
logger.Error("Response code was {0}. {1}", response.StatusCode, response.StatusDescription);
result.Source = Source.Error;
}
}
}
}
} catch (Exception ex) {
logger.Error("Can not read url. {0}", ex.Message);
result.Source = Source.Error;
}
return result;
}
示例4: VerifyNamespaces
public static bool VerifyNamespaces(this Topology topology, ILogger logger, string prefix)
{
if (string.IsNullOrEmpty(prefix))
return true;
var exchanges = topology.Exchanges.Where(e => !Matches(e.Name, prefix)).ToList();
var queues = topology.Queues.Where(q => !Matches(q.Name, prefix)).ToList();
if (exchanges.Count > 0 && queues.Count > 0)
{
logger.Error(Strings.LogInvalidNamespacesExchangeQueue, prefix, exchanges.Select(e => e.Name).ToArray(), queues.Select(q => q.Name).ToArray());
return false;
}
if (exchanges.Count > 0)
{
logger.Error(Strings.LogInvalidNamespacesExchange, prefix, exchanges.Select(e => e.Name).ToArray());
return false;
}
// ReSharper disable once InvertIf - hurts readability in this case in my opinion
if (queues.Count > 0)
{
logger.Error(Strings.LogInvalidNamespacesQueue, prefix, queues.Select(q => q.Name).ToArray() );
return false;
}
return true;
}
示例5: SchedulerHost
private SchedulerHost(bool isPrimary, Func<Type,object> containerResolve, Func<IAppConfigRepository> repositoryResolve)
{
_traceSource = new VirtoCommerceTraceSource("VirtoCommerce.ScheduleService.Trace");
Trace.TraceInformation("SchedulerHost constructor started");
try
{
_jobScheduler = new JobScheduler(isPrimary,
t =>
{
object o;
try
{
o = containerResolve(t);
}
catch (Exception ex)
{
_traceSource.Error(ex.ToString());
throw;
}
return (IJobActivity)o;
},
repositoryResolve,_traceSource
); // reuse host container
}
catch (Exception ex)
{
_traceSource.Error(ex.ToString());
throw;
}
_traceSource.Info("SchedulerHost constructor finished");
}
示例6: DNXSolution
/// <summary>
/// Initializes a new <see cref="DNXSolution"/>.
/// </summary>
/// <param name="path">Path of the directory that contains the project.json file.</param>
/// <param name="logger">Logger to use. Must not be null.</param>
/// <param name="projectFilter">Optional project filter.</param>
public DNXSolution( string path, ILogger logger, Func<DNXProjectFile, bool> projectFilter = null )
{
if( path == null ) throw new ArgumentNullException( nameof( path ) );
if( logger == null ) throw new ArgumentNullException( nameof( logger ) );
_logger = logger;
_solutionDir = FindDirectoryFrom( path, ".git" );
if( _solutionDir == null ) _logger.Error( ".git directory not found." );
else
{
_solutionDir = _solutionDir.Remove( _solutionDir.Length - 4 );
_projects = Directory.EnumerateFiles( _solutionDir, "project.json", SearchOption.AllDirectories )
.Where( p => p.IndexOf( @"\bin\", _solutionDir.Length ) < 0 )
.Select( p => new DNXProjectFile( this, p ) )
.Where( p => projectFilter == null || projectFilter( p ) )
.ToArray();
var dup = _projects.GroupBy( p => p.ProjectName, StringComparer.OrdinalIgnoreCase )
.Where( g => g.Count() > 1 );
if( dup.Any() )
{
_logger.Error( String.Format( "Duplicate names found for projects: {0}.", String.Join( ", ", dup.SelectMany( g => g.Select( p => p.RelativeProjectFilePath ) ) ) ) );
_projects = null;
}
}
}
示例7: parse
public static Message parse(byte[] data, ILogger logger)
{
if (data.Length < 4)
{
logger.Error("[parse(byte[])] Really to short");
return null;
}
long len = uIntToLong(data[0], data[1], data[2], data[3]);
//Message not fully read
if (data.Length < len + 4)
{
logger.Error("[parse(byte[])] not enough data for len: " + len);
return null;
}
//drops 4 bytes (length information)
byte[] messageData = new byte[len];
Array.Copy(data, 4, messageData, 0, len);
Message msg = deserializeBinary(messageData);
msg._logger = logger;
msg._data = data;
return msg;
}
示例8: Process
public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory)
{
var nugetNamePattern = args.FirstOrDefault();
if (nugetNamePattern == null || nugetNamePattern.StartsWith("-") || nugetNamePattern.EndsWith("\"")) {
logger.Error("No nuget pattern specified");
return true;
}
var nugetComponent = components.FindComponent<INugetSpec>(nugetNamePattern);
if (nugetComponent == null)
return true;
logger.Info("== Nuget to add: {0}", nugetComponent);
var componentNamePattern = args.LastOrDefault();
if (componentNamePattern == null || componentNamePattern.StartsWith("-") || componentNamePattern.EndsWith("\"")) {
logger.Error("No component pattern specified");
return true;
}
var specificComponent = components.FindComponent<IProject>(componentNamePattern);
if (specificComponent == null)
return true;
logger.Info("== Component to reference nuget: {0}", specificComponent);
if (specificComponent == nugetComponent) {
logger.Error("Nuget can't be added to itself");
return true;
}
specificComponent.AddNuget(logger, nugetComponent, components, packagesOutputDirectory);
return true;
}
示例9: Read
public ReaderResult Read(string resource, ILogger logger) {
var result = new ReaderResult { Source = Source.File };
var queryStringIndex = resource.IndexOf('?');
if (queryStringIndex > 0) {
result.Parameters = HttpUtility.ParseQueryString(resource.Substring(queryStringIndex+1));
resource = resource.Substring(0, queryStringIndex);
}
if (Path.HasExtension(resource)) {
if (!Path.IsPathRooted(resource)) {
resource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, resource);
}
var fileInfo = new FileInfo(resource);
try {
result.Content = File.ReadAllText(fileInfo.FullName);
} catch (Exception ex) {
logger.Error("Can not read file. {0}", ex.Message);
result.Source = Source.Error;
}
} else {
logger.Error("Invalid file name: {0}. File must have an extension (e.g. xml, json, etc)", resource);
result.Source = Source.Error;
}
return result;
}
示例10: Process
public void Process(MethodInterceptionArgs args, ILogger log)
{
try
{
args.Proceed();
}
catch (DefaultException ex)
{
log.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
var url = urlHelper.Action("OperationError", "Error", new { area = "" });
url += "/" + ex.Message;
var result = new RedirectResult(url);
args.ReturnValue = result;
}
catch (Exception ex)
{
log.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
var url = urlHelper.Action("Index", "Error", new { area = "" });
var result = new RedirectResult(url);
args.ReturnValue = result;
}
}
示例11: PostImporter
public PostImporter()
{
_checkpoint = new FileCheckpoint("postsLoaded");
_logger = new EventStore.ClientAPI.Common.Log.ConsoleLogger();
var _connectionSettings =
ConnectionSettings.Create()
.UseConsoleLogger()
.KeepReconnecting()
.KeepRetrying()
.OnConnected(_ => _logger.Info("Event Store Connected"))
.OnDisconnected(_ => _logger.Error("Event Store Disconnected"))
.OnReconnecting(_ => _logger.Info("Event Store Reconnecting"))
.OnErrorOccurred((c, e) => _logger.Error(e, "Event Store Error :("));
_connection = EventStoreConnection.Create(_connectionSettings, new IPEndPoint(IPAddress.Parse("192.81.222.61"), 1113));
_connection.Connect();
ThreadPool.SetMaxThreads(20, 20);
ThreadPool.SetMinThreads(20, 20);
//ServicePointManager.DefaultConnectionLimit = 1000;
ServicePointManager.Expect100Continue = false;
ServicePointManager.ServerCertificateValidationCallback = Validator;
//ServicePointManager.EnableDnsRoundRobin = false;
//ServicePointManager.DnsRefreshTimeout = Int32.MaxValue;
}
示例12: ExecuteTool
public static bool ExecuteTool(ILogger logger, string toolName, string arguments, string workingDirectory, Action<ILogger, string> processToolOutput = null)
{
try {
if (processToolOutput == null)
processToolOutput = (l, s) => l.Info(s);
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = toolName.FindInPathEnvironmentVariable();
p.StartInfo.Arguments = arguments;
p.StartInfo.WorkingDirectory = workingDirectory;
p.StartInfo.CreateNoWindow = true;
if (logger != null) {
p.OutputDataReceived += (object sender, DataReceivedEventArgs e) => processToolOutput(logger, e.Data);
p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => logger.Error(e.Data);
}
var debugLine = "Executing: " + p.StartInfo.FileName + " " + arguments;
logger.Debug(debugLine);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
return p.ExitCode == 0;
} catch (Exception e) {
logger.Error(e);
}
return false;
}
示例13: Execute
public void Execute(ILogger logger)
{
logger.Info("AdoInspector: Starting to replace DbProviderFactory");
//This forces the creation
try
{
DbProviderFactories.GetFactory("Anything");
}
catch (ArgumentException ex)
{
}
//Find the registered providers
var table = Support.FindDbProviderFactoryTable();
//Run through and replace providers
foreach (var row in table.Rows.Cast<DataRow>().ToList())
{
DbProviderFactory factory;
try
{
factory = DbProviderFactories.GetFactory(row);
logger.Info("AdoInspector: Successfully retrieved factory - {0}", row["Name"]);
}
catch (Exception)
{
logger.Error("AdoInspector: Failed to retrieve factory - {0}", row["Name"]);
continue;
}
//Check that we haven't already wrapped things up
if (factory is GlimpseDbProviderFactory)
{
logger.Error("AdoInspector: Factory is already wrapped - {0}", row["Name"]);
continue;
}
var proxyType = typeof(GlimpseDbProviderFactory<>).MakeGenericType(factory.GetType());
var newRow = table.NewRow();
newRow["Name"] = row["Name"];
newRow["Description"] = row["Description"];
newRow["InvariantName"] = row["InvariantName"];
newRow["AssemblyQualifiedName"] = proxyType.AssemblyQualifiedName;
table.Rows.Remove(row);
table.Rows.Add(newRow);
logger.Info("AdoInspector: Successfully replaced - {0}", newRow["Name"]);
}
logger.Info("AdoInspector: Finished replacing DbProviderFactory");
}
示例14: Run
public static void Run(AssetItem assetItem, ILogger log, AssetAnalysisParameters parameters)
{
if (assetItem == null) throw new ArgumentNullException(nameof(assetItem));
if (log == null) throw new ArgumentNullException(nameof(log));
if (parameters == null) throw new ArgumentNullException(nameof(parameters));
if (assetItem.Package == null)
{
throw new InvalidOperationException("AssetItem must belong to an existing package");
}
var package = assetItem.Package;
// Check that there is no duplicate in assets
if (package.Session != null)
{
var packages = package.FindDependencies();
foreach (var otherPackage in packages)
{
var existingAsset = otherPackage.Assets.Find(assetItem.Id);
if (existingAsset != null)
{
log.Error("Assets [{0}] with id [{1}] from Package [{2}] is already loaded from package [{3}]", existingAsset.FullPath, existingAsset.Id, package.FullPath, existingAsset.Package.FullPath);
}
else
{
existingAsset = otherPackage.Assets.Find(assetItem.Location);
if (existingAsset != null)
{
log.Error("Assets [{0}] with location [{1}] from Package [{2}] is already loaded from package [{3}]", existingAsset.FullPath, existingAsset.Location, package.FullPath, existingAsset.Package.FullPath);
}
}
}
}
var assetReferences = AssetReferenceAnalysis.Visit(assetItem.Asset);
if (package.Session != null && parameters.IsProcessingAssetReferences)
{
UpdateAssetReferences(assetItem, assetReferences, log, parameters);
}
// Update paths for asset items
if (parameters.IsProcessingUPaths)
{
// Find where this asset item was previously stored (in a different package for example)
CommonAnalysis.UpdatePaths(assetItem, assetReferences.Where(link => link.Reference is UPath), parameters);
// Source hashes are not processed by analysis, we need to manually indicate them to update
SourceHashesHelper.UpdateUPaths(assetItem.Asset, assetItem.FullPath.GetParent(), parameters.ConvertUPathTo);
}
}
示例15: Detect
public Source Detect(string resource, ILogger logger) {
if (resource == null) {
logger.Error("The configuration passed in is null.");
return Source.Error;
}
resource = resource.Trim();
if (resource == string.Empty) {
logger.Error("The configuration passed in is empty");
return Source.Error;
}
if (resource.StartsWith("<", StringComparison.Ordinal))
return Source.Xml;
if (resource.StartsWith("{", StringComparison.Ordinal))
return Source.Json;
try {
return new Uri(resource).IsFile ? Source.File : Source.Url;
} catch (Exception) {
var queryStringIndex = resource.IndexOf('?');
if (queryStringIndex > 0) {
resource = resource.Substring(0, queryStringIndex);
}
var fileName = Path.GetFileName(resource);
if (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) {
logger.Error("Your configuration contains invalid characters");
return Source.Error;
}
if (!Path.HasExtension(resource)) {
logger.Error("Your file needs an extension.");
return Source.Error;
}
if (!Path.IsPathRooted(resource)) {
resource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, resource);
}
if (new FileInfo(resource).Exists) {
return Source.File;
}
logger.Error("This source detector cannot detect your configuration source. The configuration you passed in does not appear to be JSON, XML, a Uri, or a file name.");
return Source.Error;
}
}