本文整理汇总了C#中ILogger.?.LogError方法的典型用法代码示例。如果您正苦于以下问题:C# ILogger.?.LogError方法的具体用法?C# ILogger.?.LogError怎么用?C# ILogger.?.LogError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ILogger
的用法示例。
在下文中一共展示了ILogger.?.LogError方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateUserProfile
public IUserProfileServiceResult CreateUserProfile(IUserCredentials credentials, ILogger logger) {
// Future: Switching Broker service to network service will eliminate the need for login here
// The same holds true for profile deletion. The login token can be obtained via cross process
// handle duplication
IntPtr token = IntPtr.Zero;
IntPtr password = IntPtr.Zero;
RUserProfileServiceResponse result = new RUserProfileServiceResponse(13, false, string.Empty);
uint error = 0;
try {
password = Marshal.SecureStringToGlobalAllocUnicode(credentials.Password);
if (LogonUser(credentials.Username, credentials.Domain, password, (int)LogonType.LOGON32_LOGON_NETWORK, (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out token)) {
WindowsIdentity winIdentity = new WindowsIdentity(token);
StringBuilder profileDir = new StringBuilder(MAX_PATH);
uint size = (uint)profileDir.Capacity;
bool profileExists = false;
error = CreateProfile(winIdentity.User.Value, credentials.Username, profileDir, size);
// 0x800700b7 - Profile already exists.
if (error != 0 && error != 0x800700b7) {
logger?.LogError(Resources.Error_UserProfileCreateFailed, credentials.Domain, credentials.Username, error);
result = RUserProfileServiceResponse.Blank;
} else if (error == 0x800700b7) {
profileExists = true;
logger?.LogInformation(Resources.Info_UserProfileAlreadyExists, credentials.Domain, credentials.Username);
} else {
logger?.LogInformation(Resources.Info_UserProfileCreated, credentials.Domain, credentials.Username);
}
profileDir = new StringBuilder(MAX_PATH * 2);
size = (uint)profileDir.Capacity;
if (GetUserProfileDirectory(token, profileDir, ref size)) {
logger?.LogInformation(Resources.Info_UserProfileDirectoryFound, credentials.Domain, credentials.Username, profileDir.ToString());
result = new RUserProfileServiceResponse(0, profileExists, profileDir.ToString());
} else {
logger?.LogError(Resources.Error_UserProfileDirectoryWasNotFound, credentials.Domain, credentials.Username, Marshal.GetLastWin32Error());
result = new RUserProfileServiceResponse((uint)Marshal.GetLastWin32Error(), profileExists, profileDir.ToString());
}
} else {
logger?.LogError(Resources.Error_UserLogonFailed, credentials.Domain, credentials.Username, Marshal.GetLastWin32Error());
result = new RUserProfileServiceResponse((uint)Marshal.GetLastWin32Error(), false, null);
}
} finally {
if (token != IntPtr.Zero) {
CloseHandle(token);
}
if(password != IntPtr.Zero) {
Marshal.ZeroFreeGlobalAllocUnicode(password);
}
}
return result;
}
示例2: ProcessExitedAsync
private static async Task ProcessExitedAsync(ILogger logger = null) {
if (AutoRestart && ++_autoRestartCount <= AutoRestartMaxCount) {
try {
await CreateOrAttachToBrokerInstanceAsync();
} catch (Exception ex) when (!ex.IsCriticalException()) {
logger?.LogError(Resources.Error_AutoRestartFailed, ex.Message);
}
}
}
示例3: ProfileWorkerAsync
private static async Task ProfileWorkerAsync( Func<int,int, IUserProfileServices,CancellationToken, ILogger, Task> action, int serverTimeOutms, int clientTimeOutms, ManualResetEvent workerDone, CancellationToken ct, ILogger logger) {
while (!ct.IsCancellationRequested) {
try {
await action?.Invoke(ServiceReadAfterConnectTimeoutMs, ClientResponseReadTimeoutMs, null, ct, logger);
} catch (Exception ex) when (!ex.IsCriticalException()) {
logger?.LogError(Resources.Error_UserProfileServiceError, ex.Message);
}
}
workerDone.Set();
}
示例4: MainAsync
public static async Task MainAsync(string[] args)
{
if (args.Length > 0 && string.Equals("dbg", args[0], StringComparison.OrdinalIgnoreCase))
{
args = args.Skip(1).ToArray();
Debugger.Launch();
}
NgJob job = null;
try
{
// Get arguments
var arguments = CommandHelpers.GetArguments(args, 1);
// Configure ApplicationInsights
ApplicationInsights.Initialize(arguments.GetOrDefault<string>(Arguments.InstrumentationKey));
// Create an ILoggerFactory
var loggerConfiguration = LoggingSetup.CreateDefaultLoggerConfiguration(withConsoleLogger: true);
var loggerFactory = LoggingSetup.CreateLoggerFactory(loggerConfiguration, LogEventLevel.Debug);
// Create a logger that is scoped to this class (only)
_logger = loggerFactory.CreateLogger<Program>();
var cancellationTokenSource = new CancellationTokenSource();
if (args.Length == 0)
{
throw new ArgumentException("Missing tool specification");
}
var jobName = args[0];
LogContext.PushProperty("JobName", jobName);
job = NgJobFactory.GetJob(jobName, loggerFactory);
await job.Run(arguments, cancellationTokenSource.Token);
}
catch (ArgumentException ae)
{
_logger?.LogError("A required argument was not found or was malformed/invalid: {Exception}", ae);
Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase());
}
catch (Exception e)
{
_logger?.LogCritical("A critical exception occured in ng.exe! {Exception}", e);
}
Trace.Close();
TelemetryConfiguration.Active.TelemetryChannel.Flush();
}
示例5: ProfileServiceOperationAsync
private static async Task ProfileServiceOperationAsync(Func<IUserCredentials, ILogger, IUserProfileServiceResult> operation, string name, int serverTimeOutms = 0, int clientTimeOutms = 0, CancellationToken ct = default(CancellationToken), ILogger logger = null) {
using (NamedPipeServerStream server = NamedPipeServerStreamFactory.Create(name)) {
await server.WaitForConnectionAsync(ct);
ManualResetEventSlim forceDisconnect = new ManualResetEventSlim(false);
try {
if (serverTimeOutms + clientTimeOutms > 0) {
Task.Run(() => {
// This handles Empty string input cases. This is usually the case were client is connected and writes a empty string.
// on the server side this blocks the ReadAsync indefinitely (even with the cancellation set). The code below protects
// the server from being indefinitely blocked by a malicious client.
forceDisconnect.Wait(serverTimeOutms + clientTimeOutms);
if (server.IsConnected) {
server.Disconnect();
logger?.LogError(Resources.Error_ClientTimedOut);
}
}).DoNotWait();
}
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(ct)) {
if (serverTimeOutms > 0) {
cts.CancelAfter(serverTimeOutms);
}
byte[] requestRaw = new byte[1024];
int bytesRead = 0;
while (bytesRead == 0 && !cts.IsCancellationRequested) {
bytesRead = await server.ReadAsync(requestRaw, 0, requestRaw.Length, cts.Token);
}
string json = Encoding.Unicode.GetString(requestRaw, 0, bytesRead);
var requestData = Json.DeserializeObject<RUserProfileServiceRequest>(json);
var result = operation?.Invoke(requestData, logger);
string jsonResp = JsonConvert.SerializeObject(result);
byte[] respData = Encoding.Unicode.GetBytes(jsonResp);
await server.WriteAsync(respData, 0, respData.Length, cts.Token);
await server.FlushAsync(cts.Token);
}
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(ct)) {
if (clientTimeOutms > 0) {
cts.CancelAfter(clientTimeOutms);
}
// Waiting here to allow client to finish reading client should disconnect after reading.
byte[] requestRaw = new byte[1024];
int bytesRead = 0;
while (bytesRead == 0 && !cts.Token.IsCancellationRequested) {
bytesRead = await server.ReadAsync(requestRaw, 0, requestRaw.Length, cts.Token);
}
// if there was an attempt to write, disconnect.
server.Disconnect();
}
} finally {
// server work is done.
forceDisconnect.Set();
}
}
}
示例6: DeleteUserProfile
public IUserProfileServiceResult DeleteUserProfile(IUserCredentials credentials, ILogger logger) {
logger?.LogInformation(Resources.Info_DeletingUserProfile, credentials.Domain, credentials.Username);
IntPtr token = IntPtr.Zero;
IntPtr password = IntPtr.Zero;
int error = 0;
string sid=string.Empty;
StringBuilder profileDir = new StringBuilder(MAX_PATH * 2);
uint size = (uint)profileDir.Capacity;
bool profileExists = false;
try {
password = Marshal.SecureStringToGlobalAllocUnicode(credentials.Password);
if (LogonUser(credentials.Username, credentials.Domain, password, (int)LogonType.LOGON32_LOGON_NETWORK, (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out token)) {
WindowsIdentity winIdentity = new WindowsIdentity(token);
if (GetUserProfileDirectory(token, profileDir, ref size) && !string.IsNullOrWhiteSpace(profileDir.ToString())) {
sid = winIdentity.User.Value;
profileExists = true;
} else {
error = Marshal.GetLastWin32Error();
logger?.LogError(Resources.Error_UserProfileDirectoryWasNotFound, credentials.Domain, credentials.Username, error);
}
}
} finally {
if (token != IntPtr.Zero) {
CloseHandle(token);
}
if (password != IntPtr.Zero) {
Marshal.ZeroFreeGlobalAllocUnicode(password);
}
}
string profile = "<deleted>";
if (!string.IsNullOrWhiteSpace(sid)) {
if (DeleteProfile(sid, null, null)) {
logger?.LogInformation(Resources.Info_DeletedUserProfile, credentials.Domain, credentials.Username);
} else {
error = Marshal.GetLastWin32Error();
logger?.LogError(Resources.Error_DeleteUserProfileFailed, credentials.Domain, credentials.Username, error);
profile = profileDir.ToString();
}
}
return new RUserProfileServiceResponse((uint)error, profileExists, profile);
}
示例7: StopBrokerInstanceAsync
public static async Task<int> StopBrokerInstanceAsync(ILogger logger = null) {
await TaskUtilities.SwitchToBackgroundThread();
lock (_stopBrokerInstanceLock) {
int id = _brokerProcess?.Id ?? 0;
try {
AutoRestart = false;
_brokerProcess?.Kill();
_brokerProcess = null;
} catch (Exception ex) when (!ex.IsCriticalException()) {
logger?.LogError(Resources.Error_StopBrokerFailed, ex.Message);
}
return id;
}
}
示例8: DownloadMetadata2Catalog
public static async Task<DateTime> DownloadMetadata2Catalog(HttpClient client, SortedList<DateTime, IList<PackageDetails>> packages, Storage storage, DateTime lastCreated, DateTime lastEdited, DateTime lastDeleted, bool? createdPackages, CancellationToken cancellationToken, ILogger logger)
{
var writer = new AppendOnlyCatalogWriter(storage, maxPageSize: 550);
var lastDate = DetermineLastDate(lastCreated, lastEdited, createdPackages);
if (packages == null || packages.Count == 0)
{
return lastDate;
}
foreach (var entry in packages)
{
foreach (var packageItem in entry.Value)
{
// When downloading the package binary, add a query string parameter
// that corresponds to the operation's timestamp.
// This query string will ensure the package is not cached
// (e.g. on the CDN) and returns the "latest and greatest" package metadata.
var packageUri = Utilities.GetNugetCacheBustingUri(packageItem.ContentUri, entry.Key.ToString("O"));
var response = await client.GetAsync(packageUri, cancellationToken);
if (response.IsSuccessStatusCode)
{
using (var stream = await response.Content.ReadAsStreamAsync())
{
CatalogItem item = Utils.CreateCatalogItem(
packageItem.ContentUri.ToString(),
stream,
packageItem.CreatedDate,
packageItem.LastEditedDate,
packageItem.PublishedDate);
if (item != null)
{
writer.Add(item);
logger?.LogInformation("Add metadata from: {PackageDetailsContentUri}", packageItem.ContentUri);
}
else
{
logger?.LogWarning("Unable to extract metadata from: {PackageDetailsContentUri}", packageItem.ContentUri);
}
}
}
else
{
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// the feed is out of sync with the actual package storage - if we don't have the package there is nothing to be done we might as well move onto the next package
logger?.LogWarning("Unable to download: {PackageDetailsContentUri}. Http status: {HttpStatusCode}", packageItem.ContentUri, response.StatusCode);
}
else
{
// this should trigger a restart - of this program - and not move the cursor forward
logger?.LogError("Unable to download: {PackageDetailsContentUri}. Http status: {HttpStatusCode}", packageItem.ContentUri, response.StatusCode);
throw new Exception(
$"Unable to download: {packageItem.ContentUri} http status: {response.StatusCode}");
}
}
}
lastDate = entry.Key;
}
if (createdPackages.HasValue)
{
lastCreated = createdPackages.Value ? lastDate : lastCreated;
lastEdited = !createdPackages.Value ? lastDate : lastEdited;
}
var commitMetadata = PackageCatalog.CreateCommitMetadata(writer.RootUri, new CommitMetadata(lastCreated, lastEdited, lastDeleted));
await writer.Commit(commitMetadata, cancellationToken);
logger?.LogInformation("COMMIT metadata to catalog.");
return lastDate;
}