diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..0c0ab960a --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +CONTRIBUTORS.md merge=union diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index b902f2476..000000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -1. Don't sneakily relicense free software. -2. Don't continually nag users to give you money. -3. Don't hide binary blobs in otherwise free software. -4. Don't needlessly obfuscate the build process or any other part of free software. diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fd9bab8cc..3a2c229d1 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -4,6 +4,10 @@ - [nvllsvm](https://github.com/nvllsvm) - [JustAMan](https://github.com/JustAMan) - [dcrdev](https://github.com/dcrdev) + - [EraYaN](https://github.com/EraYaN) + - [flemse](https://github.com/flemse) + - [bfayers](https://github.com/bfayers) + - [Bond_009](https://github.com/Bond-009) # Emby Contributors diff --git a/Emby.Dlna/ConnectionManager/ConnectionManager.cs b/Emby.Dlna/ConnectionManager/ConnectionManager.cs index 3f33f3ebf..ab747d189 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManager.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManager.cs @@ -2,9 +2,9 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using Emby.Dlna.Service; -using MediaBrowser.Model.Logging; using System.Collections.Generic; using MediaBrowser.Model.Xml; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.ConnectionManager { diff --git a/Emby.Dlna/ConnectionManager/ControlHandler.cs b/Emby.Dlna/ConnectionManager/ControlHandler.cs index ae983c5e7..7e3e5f650 100644 --- a/Emby.Dlna/ConnectionManager/ControlHandler.cs +++ b/Emby.Dlna/ConnectionManager/ControlHandler.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration; using Emby.Dlna.Server; using Emby.Dlna.Service; using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Model.Xml; diff --git a/Emby.Dlna/ContentDirectory/ContentDirectory.cs b/Emby.Dlna/ContentDirectory/ContentDirectory.cs index 0aabe099c..7c809a952 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectory.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectory.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using Emby.Dlna.Service; using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Controller.MediaEncoding; diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 91ec54b55..57d4078a5 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -12,7 +12,7 @@ using Emby.Dlna.Service; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; @@ -68,7 +68,7 @@ namespace Emby.Dlna.ContentDirectory _profile = profile; _config = config; - _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, Logger, libraryManager, mediaEncoder); + _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, _logger, libraryManager, mediaEncoder); } protected override IEnumerable> GetResult(string methodName, IDictionary methodParams) @@ -467,7 +467,7 @@ namespace Emby.Dlna.ContentDirectory IsMissing = false, ExcludeItemTypes = new[] { typeof(Game).Name, typeof(Book).Name }, IsFolder = isFolder, - MediaTypes = mediaTypes.ToArray(mediaTypes.Count), + MediaTypes = mediaTypes.ToArray(), DtoOptions = GetDtoOptions() }); } @@ -676,7 +676,7 @@ namespace Emby.Dlna.ContentDirectory return new QueryResult { - Items = list.ToArray(list.Count), + Items = list.ToArray(), TotalRecordCount = list.Count }; } @@ -754,7 +754,7 @@ namespace Emby.Dlna.ContentDirectory return new QueryResult { - Items = list.ToArray(list.Count), + Items = list.ToArray(), TotalRecordCount = list.Count }; } @@ -859,7 +859,7 @@ namespace Emby.Dlna.ContentDirectory return new QueryResult { - Items = list.ToArray(list.Count), + Items = list.ToArray(), TotalRecordCount = list.Count }; } @@ -1026,7 +1026,7 @@ namespace Emby.Dlna.ContentDirectory var result = new QueryResult { TotalRecordCount = genresResult.TotalRecordCount, - Items = genresResult.Items.Select(i => i.Item1).ToArray(genresResult.Items.Length) + Items = genresResult.Items.Select(i => i.Item1).ToArray() }; return ToResult(result); @@ -1044,7 +1044,7 @@ namespace Emby.Dlna.ContentDirectory var result = new QueryResult { TotalRecordCount = genresResult.TotalRecordCount, - Items = genresResult.Items.Select(i => i.Item1).ToArray(genresResult.Items.Length) + Items = genresResult.Items.Select(i => i.Item1).ToArray() }; return ToResult(result); @@ -1062,7 +1062,7 @@ namespace Emby.Dlna.ContentDirectory var result = new QueryResult { TotalRecordCount = artists.TotalRecordCount, - Items = artists.Items.Select(i => i.Item1).ToArray(artists.Items.Length) + Items = artists.Items.Select(i => i.Item1).ToArray() }; return ToResult(result); @@ -1080,7 +1080,7 @@ namespace Emby.Dlna.ContentDirectory var result = new QueryResult { TotalRecordCount = artists.TotalRecordCount, - Items = artists.Items.Select(i => i.Item1).ToArray(artists.Items.Length) + Items = artists.Items.Select(i => i.Item1).ToArray() }; return ToResult(result); @@ -1099,7 +1099,7 @@ namespace Emby.Dlna.ContentDirectory var result = new QueryResult { TotalRecordCount = artists.TotalRecordCount, - Items = artists.Items.Select(i => i.Item1).ToArray(artists.Items.Length) + Items = artists.Items.Select(i => i.Item1).ToArray() }; return ToResult(result); @@ -1247,7 +1247,7 @@ namespace Emby.Dlna.ContentDirectory { var serverItems = result .Select(i => new ServerItem(i)) - .ToArray(result.Length); + .ToArray(); return new QueryResult { @@ -1334,7 +1334,7 @@ namespace Emby.Dlna.ContentDirectory }; } - Logger.Error("Error parsing item Id: {0}. Returning user root folder.", id); + _logger.LogError("Error parsing item Id: {id}. Returning user root folder.", id); return new ServerItem(_libraryManager.GetUserRootFolder()); } diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 42727bb92..7af48ae17 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -11,7 +11,7 @@ using Emby.Dlna.ContentDirectory; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using System; using System.Globalization; @@ -173,16 +173,6 @@ namespace Emby.Dlna.Didl writer.WriteFullEndElement(); } - private ILogger GetStreamBuilderLogger(DlnaOptions options) - { - if (options.EnableDebugLog) - { - return _logger; - } - - return new NullLogger(); - } - private string GetMimeType(string input) { var mime = MimeTypes.GetMimeType(input); @@ -202,7 +192,7 @@ namespace Emby.Dlna.Didl { var sources = _mediaSourceManager.GetStaticMediaSources(video, true, _user); - streamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger(options)).BuildVideoItem(new VideoOptions + streamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildVideoItem(new VideoOptions { ItemId = video.Id, MediaSources = sources.ToArray(), @@ -509,10 +499,10 @@ namespace Emby.Dlna.Didl { var sources = _mediaSourceManager.GetStaticMediaSources(audio, true, _user); - streamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger(options)).BuildAudioItem(new AudioOptions + streamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions { ItemId = audio.Id, - MediaSources = sources.ToArray(sources.Count), + MediaSources = sources.ToArray(), Profile = _profile, DeviceId = deviceId }); @@ -923,9 +913,9 @@ namespace Emby.Dlna.Didl writer.WriteFullEndElement(); } - catch (XmlException) + catch (XmlException ex) { - //_logger.Error("Error adding xml value: " + value); + _logger.LogError(ex, "Error adding xml value: {value}", name); } } @@ -935,9 +925,9 @@ namespace Emby.Dlna.Didl { writer.WriteElementString(prefix, name, namespaceUri, value); } - catch (XmlException) + catch (XmlException ex) { - //_logger.Error("Error adding xml value: " + value); + _logger.LogError(ex, "Error adding xml value: {value}", value); } } @@ -1080,9 +1070,9 @@ namespace Emby.Dlna.Didl { tag = _imageProcessor.GetImageCacheTag(item, type); } - catch + catch (Exception ex) { - + _logger.LogError(ex, "Error getting image cache tag"); } int? width = imageInfo.Width; diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 62d1eb57c..48a33757b 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -8,7 +8,7 @@ using Emby.Dlna.Profiles; using Emby.Dlna.Server; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -58,7 +58,7 @@ namespace Emby.Dlna } catch (Exception ex) { - _logger.ErrorException("Error extracting DLNA profiles.", ex); + _logger.LogError(ex, "Error extracting DLNA profiles."); } } @@ -103,7 +103,7 @@ namespace Emby.Dlna if (profile != null) { - _logger.Debug("Found matching device profile: {0}", profile.Name); + _logger.LogDebug("Found matching device profile: {0}", profile.Name); } else { @@ -117,6 +117,7 @@ namespace Emby.Dlna { var builder = new StringBuilder(); + builder.AppendLine("No matching device profile found. The default will need to be used."); builder.AppendLine(string.Format("DeviceDescription:{0}", profile.DeviceDescription ?? string.Empty)); builder.AppendLine(string.Format("FriendlyName:{0}", profile.FriendlyName ?? string.Empty)); builder.AppendLine(string.Format("Manufacturer:{0}", profile.Manufacturer ?? string.Empty)); @@ -127,7 +128,7 @@ namespace Emby.Dlna builder.AppendLine(string.Format("ModelUrl:{0}", profile.ModelUrl ?? string.Empty)); builder.AppendLine(string.Format("SerialNumber:{0}", profile.SerialNumber ?? string.Empty)); - _logger.LogMultiline("No matching device profile found. The default will need to be used.", LogSeverity.Info, builder); + _logger.LogInformation(builder.ToString()); } private bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) @@ -197,7 +198,7 @@ namespace Emby.Dlna } catch (ArgumentException ex) { - _logger.ErrorException("Error evaluating regex pattern {0}", ex, pattern); + _logger.LogError(ex, "Error evaluating regex pattern {Pattern}", pattern); return false; } } @@ -216,12 +217,12 @@ namespace Emby.Dlna if (profile != null) { - _logger.Debug("Found matching device profile: {0}", profile.Name); + _logger.LogDebug("Found matching device profile: {0}", profile.Name); } else { var headerString = string.Join(", ", headers.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); - _logger.Debug("No matching device profile found. {0}", headerString); + _logger.LogDebug("No matching device profile found. {0}", headerString); } return profile; @@ -250,7 +251,7 @@ namespace Emby.Dlna return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase); case HeaderMatchType.Substring: var isMatch = value.IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1; - //_logger.Debug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch); + //_logger.LogDebug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch); return isMatch; case HeaderMatchType.Regex: return Regex.IsMatch(value, header.Value, RegexOptions.IgnoreCase); @@ -323,7 +324,7 @@ namespace Emby.Dlna } catch (Exception ex) { - _logger.ErrorException("Error parsing profile file: {0}", ex, path); + _logger.LogError(ex, "Error parsing profile file: {Path}", path); return null; } @@ -530,8 +531,8 @@ namespace Emby.Dlna }; } } - - class DlnaProfileEntryPoint /*: IServerEntryPoint*/ + /* + class DlnaProfileEntryPoint : IServerEntryPoint { private readonly IApplicationPaths _appPaths; private readonly IFileSystem _fileSystem; @@ -551,7 +552,7 @@ namespace Emby.Dlna private void DumpProfiles() { - var list = new List + DeviceProfile[] list = new [] { new SamsungSmartTvProfile(), new XboxOneProfile(), @@ -596,5 +597,5 @@ namespace Emby.Dlna public void Dispose() { } - } -} \ No newline at end of file + }*/ +} diff --git a/Emby.Dlna/Eventing/EventManager.cs b/Emby.Dlna/Eventing/EventManager.cs index 0638cff89..ea9ba3f22 100644 --- a/Emby.Dlna/Eventing/EventManager.cs +++ b/Emby.Dlna/Eventing/EventManager.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -34,7 +34,7 @@ namespace Emby.Dlna.Eventing // Remove logging for now because some devices are sending this very frequently // TODO re-enable with dlna debug logging setting - //_logger.Debug("Renewing event subscription for {0} with timeout of {1} to {2}", + //_logger.LogDebug("Renewing event subscription for {0} with timeout of {1} to {2}", // subscription.NotificationType, // timeout, // subscription.CallbackUrl); @@ -60,7 +60,7 @@ namespace Emby.Dlna.Eventing // Remove logging for now because some devices are sending this very frequently // TODO re-enable with dlna debug logging setting - //_logger.Debug("Creating event subscription for {0} with timeout of {1} to {2}", + //_logger.LogDebug("Creating event subscription for {0} with timeout of {1} to {2}", // notificationType, // timeout, // callbackUrl); @@ -96,7 +96,7 @@ namespace Emby.Dlna.Eventing public EventSubscriptionResponse CancelEventSubscription(string subscriptionId) { - _logger.Debug("Cancelling event subscription {0}", subscriptionId); + _logger.LogDebug("Cancelling event subscription {0}", subscriptionId); EventSubscription sub; _subscriptions.TryRemove(subscriptionId, out sub); diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index cd535a98a..6ab0767a5 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -11,7 +11,7 @@ using MediaBrowser.Controller.Session; using MediaBrowser.Controller.TV; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading.Tasks; @@ -64,7 +64,7 @@ namespace Emby.Dlna.Main public static DlnaEntryPoint Current; public DlnaEntryPoint(IServerConfigurationManager config, - ILogManager logManager, + ILoggerFactory loggerFactory, IServerApplicationHost appHost, ISessionManager sessionManager, IHttpClient httpClient, @@ -102,7 +102,7 @@ namespace Emby.Dlna.Main _timerFactory = timerFactory; _environmentInfo = environmentInfo; _networkManager = networkManager; - _logger = logManager.GetLogger("Dlna"); + _logger = loggerFactory.CreateLogger("Dlna"); ContentDirectory = new ContentDirectory.ContentDirectory(dlnaManager, userDataManager, @@ -185,13 +185,13 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.ErrorException("Error starting ssdp handlers", ex); + _logger.LogError(ex, "Error starting ssdp handlers"); } } private void LogMessage(string msg) { - _logger.Debug(msg); + _logger.LogDebug(msg); } private void StartDeviceDiscovery(ISsdpCommunicationsServer communicationsServer) @@ -202,7 +202,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.ErrorException("Error starting device discovery", ex); + _logger.LogError(ex, "Error starting device discovery"); } } @@ -210,12 +210,12 @@ namespace Emby.Dlna.Main { try { - _logger.Info("Disposing DeviceDiscovery"); + _logger.LogInformation("Disposing DeviceDiscovery"); ((DeviceDiscovery)_deviceDiscovery).Dispose(); } catch (Exception ex) { - _logger.ErrorException("Error stopping device discovery", ex); + _logger.LogError(ex, "Error stopping device discovery"); } } @@ -243,7 +243,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.ErrorException("Error registering endpoint", ex); + _logger.LogError(ex, "Error registering endpoint"); } } @@ -263,7 +263,7 @@ namespace Emby.Dlna.Main var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; - _logger.Info("Registering publisher for {0} on {1}", fullService, address.ToString()); + _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address.ToString()); var descriptorUri = "/dlna/" + udn + "/description.xml"; var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri); @@ -361,7 +361,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.ErrorException("Error starting PlayTo manager", ex); + _logger.LogError(ex, "Error starting PlayTo manager"); } } } @@ -374,12 +374,12 @@ namespace Emby.Dlna.Main { try { - _logger.Info("Disposing PlayToManager"); + _logger.LogInformation("Disposing PlayToManager"); _manager.Dispose(); } catch (Exception ex) { - _logger.ErrorException("Error disposing PlayTo manager", ex); + _logger.LogError(ex, "Error disposing PlayTo manager"); } _manager = null; } @@ -394,7 +394,7 @@ namespace Emby.Dlna.Main if (_communicationsServer != null) { - _logger.Info("Disposing SsdpCommunicationsServer"); + _logger.LogInformation("Disposing SsdpCommunicationsServer"); _communicationsServer.Dispose(); _communicationsServer = null; } @@ -409,7 +409,7 @@ namespace Emby.Dlna.Main { if (_Publisher != null) { - _logger.Info("Disposing SsdpDevicePublisher"); + _logger.LogInformation("Disposing SsdpDevicePublisher"); _Publisher.Dispose(); _Publisher = null; } diff --git a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs index daf46b106..d1a595de0 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Configuration; using Emby.Dlna.Server; using Emby.Dlna.Service; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Model.Xml; diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs index 4ed74a684..f07af0464 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using Emby.Dlna.Service; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Model.Xml; diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index 9a861b8c7..13bed6b2f 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Configuration; using Emby.Dlna.Common; using Emby.Dlna.Ssdp; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using System; using System.Collections.Generic; @@ -108,7 +108,7 @@ namespace Emby.Dlna.PlayTo public void Start() { - _logger.Debug("Dlna Device.Start"); + _logger.LogDebug("Dlna Device.Start"); _timer = _timerFactory.Create(TimerCallback, null, 1000, Timeout.Infinite); } @@ -140,7 +140,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error updating device volume info for {0}", ex, Properties.Name); + _logger.LogError(ex, "Error updating device volume info for {DeviceName}", Properties.Name); } } @@ -259,7 +259,7 @@ namespace Emby.Dlna.PlayTo return false; } - _logger.Debug("Setting mute"); + _logger.LogDebug("Setting mute"); var value = mute ? 1 : 0; await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value)) @@ -323,7 +323,7 @@ namespace Emby.Dlna.PlayTo url = url.Replace("&", "&"); - _logger.Debug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header); + _logger.LogDebug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI"); if (command == null) @@ -507,7 +507,7 @@ namespace Emby.Dlna.PlayTo if (_disposed) return; - //_logger.ErrorException("Error updating device info for {0}", ex, Properties.Name); + _logger.LogError(ex, "Error updating device info for {DeviceName}", Properties.Name); _connectFailureCount++; @@ -516,7 +516,7 @@ namespace Emby.Dlna.PlayTo var action = OnDeviceUnavailable; if (action != null) { - _logger.Debug("Disposing device due to loss of connection"); + _logger.LogDebug("Disposing device due to loss of connection"); action(); return; } @@ -767,7 +767,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Unable to parse xml {0}", ex, trackString); + _logger.LogError(ex, "Unable to parse xml {0}", trackString); return new Tuple(true, null); } } @@ -887,7 +887,7 @@ namespace Emby.Dlna.PlayTo string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl); var httpClient = new SsdpHttpClient(_httpClient, _config); - _logger.Debug("Dlna Device.GetRenderingProtocolAsync"); + _logger.LogDebug("Dlna Device.GetRenderingProtocolAsync"); var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false); rendererCommands = TransportCommands.Create(document); @@ -941,7 +941,7 @@ namespace Emby.Dlna.PlayTo if (room != null && !string.IsNullOrWhiteSpace(room.Value)) friendlyNames.Add(room.Value); - deviceProperties.Name = string.Join(" ", friendlyNames.ToArray(friendlyNames.Count)); + deviceProperties.Name = string.Join(" ", friendlyNames.ToArray()); var model = document.Descendants(uPnpNamespaces.ud.GetName("modelName")).FirstOrDefault(); if (model != null) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index ce22a0af2..c51f220ef 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -7,7 +7,7 @@ using Emby.Dlna.Didl; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Session; using MediaBrowser.Model.System; using System; @@ -156,7 +156,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting progress", ex); + _logger.LogError(ex, "Error reporting progress"); } } @@ -204,7 +204,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting playback stopped", ex); + _logger.LogError(ex, "Error reporting playback stopped"); } } @@ -223,7 +223,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting progress", ex); + _logger.LogError(ex, "Error reporting progress"); } } @@ -247,7 +247,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting progress", ex); + _logger.LogError(ex, "Error reporting progress"); } } @@ -278,7 +278,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting progress", ex); + _logger.LogError(ex, "Error reporting progress"); } } @@ -319,7 +319,7 @@ namespace Emby.Dlna.PlayTo public async Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken) { - _logger.Debug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand); + _logger.LogDebug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand); var user = command.ControllingUserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(command.ControllingUserId); @@ -351,7 +351,7 @@ namespace Emby.Dlna.PlayTo } } - _logger.Debug("{0} - Playlist created", _session.DeviceName); + _logger.LogDebug("{0} - Playlist created", _session.DeviceName); if (command.PlayCommand == PlayCommand.PlayLast) { @@ -532,23 +532,13 @@ namespace Emby.Dlna.PlayTo return null; } - private ILogger GetStreamBuilderLogger() - { - if (_config.GetDlnaConfiguration().EnableDebugLog) - { - return _logger; - } - - return new NullLogger(); - } - private PlaylistItem GetPlaylistItem(BaseItem item, List mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex) { if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase)) { return new PlaylistItem { - StreamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger()).BuildVideoItem(new VideoOptions + StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildVideoItem(new VideoOptions { ItemId = item.Id, MediaSources = mediaSources.ToArray(), @@ -568,10 +558,10 @@ namespace Emby.Dlna.PlayTo { return new PlaylistItem { - StreamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger()).BuildAudioItem(new AudioOptions + StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions { ItemId = item.Id, - MediaSources = mediaSources.ToArray(mediaSources.Count), + MediaSources = mediaSources.ToArray(), Profile = profile, DeviceId = deviceId, MaxBitrate = profile.MaxStreamingBitrate, @@ -599,7 +589,7 @@ namespace Emby.Dlna.PlayTo { Playlist.Clear(); Playlist.AddRange(items); - _logger.Debug("{0} - Playing {1} items", _session.DeviceName, Playlist.Count); + _logger.LogDebug("{0} - Playing {1} items", _session.DeviceName, Playlist.Count); await SetPlaylistIndex(0).ConfigureAwait(false); return true; diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index ed3cf311b..47d00aad5 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Session; using System; using System.Collections.Generic; @@ -93,7 +93,7 @@ namespace Emby.Dlna.PlayTo if (usn.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1 && nt.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1) { - //_logger.Debug("Upnp device {0} does not contain a MediaRenderer device (0).", location); + //_logger.LogDebug("Upnp device {0} does not contain a MediaRenderer device (0).", location); return; } @@ -121,7 +121,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error creating PlayTo device.", ex); + _logger.LogError(ex, "Error creating PlayTo device."); } finally { @@ -155,9 +155,9 @@ namespace Emby.Dlna.PlayTo private async Task AddDevice(UpnpDeviceInfo info, string location, CancellationToken cancellationToken) { var uri = info.Location; - _logger.Debug("Attempting to create PlayToController from location {0}", location); + _logger.LogDebug("Attempting to create PlayToController from location {0}", location); - _logger.Debug("Logging session activity from location {0}", location); + _logger.LogDebug("Logging session activity from location {0}", location); string uuid; if (info.Headers.TryGetValue("USN", out uuid)) { @@ -237,7 +237,7 @@ namespace Emby.Dlna.PlayTo SupportsMediaControl = true }); - _logger.Info("DLNA Session created for {0} - {1}", device.Properties.Name, device.Properties.ModelName); + _logger.LogInformation("DLNA Session created for {0} - {1}", device.Properties.Name, device.Properties.ModelName); } } diff --git a/Emby.Dlna/Profiles/DefaultProfile.cs b/Emby.Dlna/Profiles/DefaultProfile.cs index b60a664ba..1295c2f9a 100644 --- a/Emby.Dlna/Profiles/DefaultProfile.cs +++ b/Emby.Dlna/Profiles/DefaultProfile.cs @@ -173,7 +173,7 @@ namespace Emby.Dlna.Profiles Value = value }); - XmlRootAttributes = list.ToArray(list.Count); + XmlRootAttributes = list.ToArray(); } } } diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index b2b742b10..ae094cc2f 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using Emby.Dlna.Server; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -20,13 +20,13 @@ namespace Emby.Dlna.Service private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"; protected readonly IServerConfigurationManager Config; - protected readonly ILogger Logger; + protected readonly ILogger _logger; protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory; protected BaseControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory) { Config = config; - Logger = logger; + _logger = logger; XmlReaderSettingsFactory = xmlReaderSettingsFactory; } @@ -52,7 +52,7 @@ namespace Emby.Dlna.Service } catch (Exception ex) { - Logger.ErrorException("Error processing control request", ex); + _logger.LogError(ex, "Error processing control request"); return new ControlErrorHandler().GetResponse(ex); } @@ -76,7 +76,7 @@ namespace Emby.Dlna.Service } } - Logger.Debug("Received control request {0}", requestInfo.LocalName); + _logger.LogDebug("Received control request {0}", requestInfo.LocalName); var result = GetResult(requestInfo.LocalName, requestInfo.Headers); @@ -118,7 +118,7 @@ namespace Emby.Dlna.Service IsSuccessful = true }; - //Logger.Debug(xml); + //logger.LogDebug(xml); controlResponse.Headers.Add("EXT", string.Empty); @@ -242,9 +242,9 @@ namespace Emby.Dlna.Service } var originalHeaders = request.Headers; - var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray(originalHeaders.Count)); + var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); - Logger.Debug("Control request. Headers: {0}", headers); + _logger.LogDebug("Control request. Headers: {0}", headers); } private void LogResponse(ControlResponse response) @@ -258,7 +258,7 @@ namespace Emby.Dlna.Service var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); //builder.Append(response.Xml); - Logger.Debug("Control response. Headers: {0}", headers); + _logger.LogDebug("Control response. Headers: {0}", headers); } } } diff --git a/Emby.Dlna/Service/BaseService.cs b/Emby.Dlna/Service/BaseService.cs index bc7f01d97..92b81a7ac 100644 --- a/Emby.Dlna/Service/BaseService.cs +++ b/Emby.Dlna/Service/BaseService.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Dlna; using Emby.Dlna.Eventing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.Service { diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index a75e065c3..85dc4d94f 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; diff --git a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs index 9a313d9d3..5de8ac383 100644 --- a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs +++ b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs @@ -4,7 +4,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.IO; using MediaBrowser.Model.IO; @@ -78,7 +78,7 @@ namespace Emby.Drawing.ImageMagick private void LogVersion() { - _logger.Info("ImageMagick version: " + GetVersion()); + _logger.LogInformation("ImageMagick version: " + GetVersion()); TestWebp(); Wand.SetMagickThreadCount(1); } @@ -101,9 +101,9 @@ namespace Emby.Drawing.ImageMagick wand.SaveImage(tmpPath); } } - catch + catch (Exception ex) { - //_logger.ErrorException("Error loading webp: ", ex); + _logger.LogError(ex, "Error loading webp"); _webpAvailable = false; } } @@ -295,7 +295,7 @@ namespace Emby.Drawing.ImageMagick } catch (Exception ex) { - _logger.ErrorException("Error drawing indicator overlay", ex); + _logger.LogError(ex, "Error drawing indicator overlay"); } } diff --git a/Emby.Drawing.Net/GDIImageEncoder.cs b/Emby.Drawing.Net/GDIImageEncoder.cs index 02e7657dd..1639125d3 100644 --- a/Emby.Drawing.Net/GDIImageEncoder.cs +++ b/Emby.Drawing.Net/GDIImageEncoder.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Drawing.Drawing2D; @@ -30,7 +30,7 @@ namespace Emby.Drawing.Net private void LogInfo() { - _logger.Info("GDIImageEncoder starting"); + _logger.LogInformation("GDIImageEncoder starting"); using (var stream = GetType().Assembly.GetManifestResourceStream(GetType().Namespace + ".empty.png")) { using (var img = Image.FromStream(stream)) @@ -38,7 +38,7 @@ namespace Emby.Drawing.Net } } - _logger.Info("GDIImageEncoder started"); + _logger.LogInformation("GDIImageEncoder started"); } public string[] SupportedInputFormats @@ -214,7 +214,7 @@ namespace Emby.Drawing.Net } catch (Exception ex) { - _logger.ErrorException("Error drawing indicator overlay", ex); + _logger.LogError(ex, "Error drawing indicator overlay"); } } diff --git a/Emby.Drawing.Skia/SkiaEncoder.cs b/Emby.Drawing.Skia/SkiaEncoder.cs index 9eb7055b4..7a445a09c 100644 --- a/Emby.Drawing.Skia/SkiaEncoder.cs +++ b/Emby.Drawing.Skia/SkiaEncoder.cs @@ -3,7 +3,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using SkiaSharp; using System; using System.IO; @@ -81,7 +81,7 @@ namespace Emby.Drawing.Skia // test an operation that requires the native library SKPMColor.PreMultiply(SKColors.Black); - _logger.Info("SkiaSharp version: " + GetVersion()); + _logger.LogInformation("SkiaSharp version: " + GetVersion()); } public static string GetVersion() @@ -530,7 +530,7 @@ namespace Emby.Drawing.Skia throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath)); } - //_logger.Info("Color type {0}", bitmap.Info.ColorType); + //_logger.LogInformation("Color type {0}", bitmap.Info.ColorType); var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height); @@ -660,7 +660,7 @@ namespace Emby.Drawing.Skia } catch (Exception ex) { - _logger.ErrorException("Error drawing indicator overlay", ex); + _logger.LogError(ex, "Error drawing indicator overlay"); } } diff --git a/Emby.Drawing/Common/ImageHeader.cs b/Emby.Drawing/Common/ImageHeader.cs index 121e20deb..7b819c2fd 100644 --- a/Emby.Drawing/Common/ImageHeader.cs +++ b/Emby.Drawing/Common/ImageHeader.cs @@ -1,5 +1,5 @@ using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -235,4 +235,4 @@ namespace Emby.Drawing.Common throw new ArgumentException(ErrorMessage); } } -} \ No newline at end of file +} diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index eeb5b8f9f..6a67be56d 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; @@ -261,7 +261,7 @@ namespace Emby.Drawing //if (originalImageSize.HasValue && options.HasDefaultOptions(originalImagePath, originalImageSize.Value) && !autoOrient) //{ // // Just spit out the original file if all the options are default - // _logger.Info("Returning original image {0}", originalImagePath); + // _logger.LogInformation("Returning original image {0}", originalImagePath); // return new ValueTuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); //} @@ -302,7 +302,7 @@ namespace Emby.Drawing { // Decoder failed to decode it #if DEBUG - _logger.ErrorException("Error encoding image", ex); + _logger.LogError(ex, "Error encoding image"); #endif // Just spit out the original file if all the options are default return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); @@ -310,7 +310,7 @@ namespace Emby.Drawing catch (Exception ex) { // If it fails for whatever reason, return the original image - _logger.ErrorException("Error encoding image", ex); + _logger.LogError(ex, "Error encoding image"); // Just spit out the original file if all the options are default return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); @@ -464,7 +464,7 @@ namespace Emby.Drawing } var path = info.Path; - _logger.Info("Getting image size for item {0} {1}", item.GetType().Name, path); + _logger.LogInformation("Getting image size for item {0} {1}", item.GetType().Name, path); var size = GetImageSize(path, allowSlowMethods); @@ -564,7 +564,7 @@ namespace Emby.Drawing var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList(); cacheKeys.Add(originalImagePath + dateModified.Ticks); - return string.Join("|", cacheKeys.ToArray(cacheKeys.Count)).GetMD5().ToString("N"); + return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N"); } private async Task> GetSupportedImage(string originalImagePath, DateTime dateModified) @@ -603,7 +603,7 @@ namespace Emby.Drawing } catch (Exception ex) { - _logger.ErrorException("Image conversion failed for {0}", ex, originalImagePath); + _logger.LogError(ex, "Image conversion failed for {originalImagePath}", originalImagePath); } } @@ -646,21 +646,21 @@ namespace Emby.Drawing var cacheGuid = GetImageCacheTag(item, image, enhancers); // Enhance if we have enhancers - var ehnancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false); + var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false); - var ehnancedImagePath = ehnancedImageInfo.Item1; + var enhancedImagePath = enhancedImageInfo.Item1; // If the path changed update dateModified - if (!string.Equals(ehnancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase)) { - var treatmentRequiresTransparency = ehnancedImageInfo.Item2; + var treatmentRequiresTransparency = enhancedImageInfo.Item2; - return new ValueTuple(ehnancedImagePath, _fileSystem.GetLastWriteTimeUtc(ehnancedImagePath), treatmentRequiresTransparency); + return new ValueTuple(enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency); } } catch (Exception ex) { - _logger.ErrorException("Error enhancing image", ex); + _logger.LogError(ex, "Error enhancing image"); } return new ValueTuple(originalImagePath, dateModified, inputImageSupportsTransparency); @@ -827,11 +827,11 @@ namespace Emby.Drawing public void CreateImageCollage(ImageCollageOptions options) { - _logger.Info("Creating image collage and saving to {0}", options.OutputPath); + _logger.LogInformation("Creating image collage and saving to {0}", options.OutputPath); _imageEncoder.CreateImageCollage(options); - _logger.Info("Completed creation of image collage and saved to {0}", options.OutputPath); + _logger.LogInformation("Completed creation of image collage and saved to {0}", options.OutputPath); } public IImageEnhancer[] GetSupportedEnhancers(BaseItem item, ImageType imageType) @@ -853,7 +853,7 @@ namespace Emby.Drawing } catch (Exception ex) { - _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name); + _logger.LogError(ex, "Error in image enhancer: {0}", i.GetType().Name); } } @@ -919,4 +919,4 @@ namespace Emby.Drawing } } } -} \ No newline at end of file +} diff --git a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs index 620d3bae9..faaed482a 100644 --- a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs +++ b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs @@ -4,7 +4,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using System.Runtime.InteropServices; @@ -20,7 +20,7 @@ namespace IsoMounter private readonly IEnvironmentInfo EnvironmentInfo; private readonly bool ExecutablesAvailable; private readonly IFileSystem FileSystem; - private readonly ILogger Logger; + private readonly ILogger _logger; private readonly string MountCommand; private readonly string MountPointRoot; private readonly IProcessFactory ProcessFactory; @@ -36,24 +36,24 @@ namespace IsoMounter EnvironmentInfo = environment; FileSystem = fileSystem; - Logger = logger; + _logger = logger; ProcessFactory = processFactory; MountPointRoot = FileSystem.DirectorySeparatorChar + "tmp" + FileSystem.DirectorySeparatorChar + "Emby"; - Logger.Debug( + _logger.LogDebug( "[{0}] System PATH is currently set to [{1}].", Name, EnvironmentInfo.GetEnvironmentVariable("PATH") ?? "" ); - Logger.Debug( + _logger.LogDebug( "[{0}] System path separator is [{1}].", Name, EnvironmentInfo.PathSeparator ); - Logger.Debug( + _logger.LogDebug( "[{0}] Mount point root is [{1}].", Name, MountPointRoot @@ -65,7 +65,7 @@ namespace IsoMounter SudoCommand = GetFullPathForExecutable("sudo"); - Logger.Info( + _logger.LogInformation( "[{0}] Using version of [sudo] located at [{1}].", Name, SudoCommand @@ -73,7 +73,7 @@ namespace IsoMounter MountCommand = GetFullPathForExecutable("mount"); - Logger.Info( + _logger.LogInformation( "[{0}] Using version of [mount] located at [{1}].", Name, MountCommand @@ -81,7 +81,7 @@ namespace IsoMounter UmountCommand = GetFullPathForExecutable("umount"); - Logger.Info( + _logger.LogInformation( "[{0}] Using version of [umount] located at [{1}].", Name, UmountCommand @@ -119,7 +119,7 @@ namespace IsoMounter { if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux) { - Logger.Info( + _logger.LogInformation( "[{0}] Checking we can attempt to mount [{1}], Extension = [{2}], Operating System = [{3}], Executables Available = [{4}].", Name, path, @@ -182,7 +182,7 @@ namespace IsoMounter return; } - Logger.Info( + _logger.LogInformation( "[{0}] Disposing [{1}].", Name, disposing.ToString() @@ -230,7 +230,7 @@ namespace IsoMounter var uid = getuid(); - Logger.Debug( + _logger.LogDebug( "[{0}] Our current UID is [{1}], GetUserId() returned [{2}].", Name, uid.ToString(), @@ -260,35 +260,29 @@ namespace IsoMounter } ); - try { - + try + { process.Start(); //StreamReader outputReader = process.StandardOutput.; //StreamReader errorReader = process.StandardError; - Logger.Debug( - "[{0}] Standard output from process is [{1}].", + _logger.LogDebug( + "[{Name}] Standard output from process is [{Error}].", Name, process.StandardOutput.ReadToEnd() ); - Logger.Debug( - "[{0}] Standard error from process is [{1}].", + _logger.LogDebug( + "[{Name}] Standard error from process is [{Error}].", Name, process.StandardError.ReadToEnd() ); - - } catch (Exception ex) { - + } + catch (Exception ex) + { processFailed = true; - - Logger.Debug( - "[{0}] Unhandled exception executing command, exception is [{1}].", - Name, - ex.Message - ); - + _logger.LogDebug(ex, "[{Name}] Unhandled exception executing command.", Name); } if (!processFailed && process.ExitCode == 0) { @@ -308,14 +302,14 @@ namespace IsoMounter if (!string.IsNullOrEmpty(isoPath)) { - Logger.Info( - "[{0}] Attempting to mount [{1}].", + _logger.LogInformation( + "[{Name}] Attempting to mount [{Path}].", Name, isoPath ); - Logger.Debug( - "[{0}] ISO will be mounted at [{1}].", + _logger.LogDebug( + "[{Name}] ISO will be mounted at [{Path}].", Name, mountPoint ); @@ -326,11 +320,16 @@ namespace IsoMounter } - try { + try + { FileSystem.CreateDirectory(mountPoint); - } catch (UnauthorizedAccessException) { + } + catch (UnauthorizedAccessException) + { throw new IOException("Unable to create mount point(Permission denied) for " + isoPath); - } catch (Exception) { + } + catch (Exception) + { throw new IOException("Unable to create mount point for " + isoPath); } @@ -342,7 +341,7 @@ namespace IsoMounter cmdArguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", MountCommand, isoPath, mountPoint); } - Logger.Debug( + _logger.LogDebug( "[{0}] Mount command [{1}], mount arguments [{2}].", Name, cmdFilename, @@ -351,7 +350,7 @@ namespace IsoMounter if (ExecuteCommand(cmdFilename, cmdArguments)) { - Logger.Info( + _logger.LogInformation( "[{0}] ISO mount completed successfully.", Name ); @@ -360,23 +359,18 @@ namespace IsoMounter } else { - Logger.Info( + _logger.LogInformation( "[{0}] ISO mount completed with errors.", Name ); - try { - + try + { FileSystem.DeleteDirectory(mountPoint, false); - - } catch (Exception ex) { - - Logger.Info( - "[{0}] Unhandled exception removing mount point, exception is [{1}].", - Name, - ex.Message - ); - + } + catch (Exception ex) + { + _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name); } mountedISO = null; @@ -395,7 +389,7 @@ namespace IsoMounter if (mount != null) { - Logger.Info( + _logger.LogInformation( "[{0}] Attempting to unmount ISO [{1}] mounted on [{2}].", Name, mount.IsoPath, @@ -416,7 +410,7 @@ namespace IsoMounter cmdArguments = string.Format("\"{0}\" \"{1}\"", UmountCommand, mount.MountedPath); } - Logger.Debug( + _logger.LogDebug( "[{0}] Umount command [{1}], umount arguments [{2}].", Name, cmdFilename, @@ -425,34 +419,28 @@ namespace IsoMounter if (ExecuteCommand(cmdFilename, cmdArguments)) { - Logger.Info( + _logger.LogInformation( "[{0}] ISO unmount completed successfully.", Name ); } else { - Logger.Info( + _logger.LogInformation( "[{0}] ISO unmount completed with errors.", Name ); } - try { - + try + { FileSystem.DeleteDirectory(mount.MountedPath, false); - - } catch (Exception ex) { - - Logger.Info( - "[{0}] Unhandled exception removing mount point, exception is [{1}].", - Name, - ex.Message - ); - } - + catch (Exception ex) + { + _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name); + } } #endregion diff --git a/Emby.IsoMounting/IsoMounter/LinuxMount.cs b/Emby.IsoMounting/IsoMounter/LinuxMount.cs index 9c60f9d0a..edd26f08d 100644 --- a/Emby.IsoMounting/IsoMounter/LinuxMount.cs +++ b/Emby.IsoMounting/IsoMounter/LinuxMount.cs @@ -79,4 +79,3 @@ namespace IsoMounter } } - diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs index bb348d267..fa8fdd9c1 100644 --- a/Emby.Notifications/NotificationManager.cs +++ b/Emby.Notifications/NotificationManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Notifications; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Notifications; using System; using System.Collections.Generic; @@ -25,11 +25,11 @@ namespace Emby.Notifications private INotificationService[] _services; private INotificationTypeFactory[] _typeFactories; - public NotificationManager(ILogManager logManager, IUserManager userManager, IServerConfigurationManager config) + public NotificationManager(ILoggerFactory loggerFactory, IUserManager userManager, IServerConfigurationManager config) { _userManager = userManager; _config = config; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); } private NotificationOptions GetConfiguration() @@ -126,7 +126,7 @@ namespace Emby.Notifications User = user }; - _logger.Debug("Sending notification via {0} to user {1}", service.Name, user.Name); + _logger.LogDebug("Sending notification via {0} to user {1}", service.Name, user.Name); try { @@ -134,7 +134,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.ErrorException("Error sending notification to {0}", ex, service.Name); + _logger.LogError(ex, "Error sending notification to {0}", service.Name); } } @@ -146,7 +146,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.ErrorException("Error in IsEnabledForUser", ex); + _logger.LogError(ex, "Error in IsEnabledForUser"); return false; } } @@ -177,7 +177,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.ErrorException("Error in GetNotificationTypes", ex); + _logger.LogError(ex, "Error in GetNotificationTypes"); return new List(); } diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/Notifications.cs index 3cadad6c8..101f9706c 100644 --- a/Emby.Notifications/Notifications.cs +++ b/Emby.Notifications/Notifications.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Notifications; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Notifications; using MediaBrowser.Model.Tasks; using System; @@ -137,7 +137,7 @@ namespace Emby.Notifications var notification = new NotificationRequest { - Description = "Please see emby.media for details.", + Description = "Please see jellyfin.media for details.", NotificationType = type, Name = _localization.GetLocalizedString("NewVersionIsAvailable") }; @@ -273,7 +273,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.ErrorException("Error sending notification", ex); + _logger.LogError(ex, "Error sending notification"); } } diff --git a/Emby.Photos/PhotoProvider.cs b/Emby.Photos/PhotoProvider.cs index 3e998997a..726fd1d79 100644 --- a/Emby.Photos/PhotoProvider.cs +++ b/Emby.Photos/PhotoProvider.cs @@ -9,7 +9,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using TagLib; using TagLib.IFD; using TagLib.IFD.Entries; @@ -170,9 +170,9 @@ namespace Emby.Photos } } } - catch (Exception e) + catch (Exception ex) { - _logger.ErrorException("Image Provider - Error reading image tag for {0}", e, item.Path); + _logger.LogError(ex, "Image Provider - Error reading image tag for {0}", item.Path); } } diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs index 079d0af0a..3f7b907a9 100644 --- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs +++ b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs @@ -10,7 +10,7 @@ using MediaBrowser.Controller.Session; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Activity; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Updates; using System; @@ -129,7 +129,7 @@ namespace Emby.Server.Implementations.Activity if (item == null) { - //_logger.Warn("PlaybackStopped reported with null media info."); + //_logger.LogWarning("PlaybackStopped reported with null media info."); return; } @@ -160,7 +160,7 @@ namespace Emby.Server.Implementations.Activity if (item == null) { - //_logger.Warn("PlaybackStart reported with null media info."); + //_logger.LogWarning("PlaybackStart reported with null media info."); return; } @@ -284,7 +284,7 @@ namespace Emby.Server.Implementations.Activity Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username), Type = "AuthenticationFailed", ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint), - Severity = LogSeverity.Error + Severity = LogLevel.Error }); } @@ -466,9 +466,9 @@ namespace Emby.Server.Implementations.Activity { Name = string.Format(_localization.GetLocalizedString("ScheduledTaskFailedWithName"), task.Name), Type = NotificationType.TaskFailed.ToString(), - Overview = string.Join(Environment.NewLine, vals.ToArray(vals.Count)), + Overview = string.Join(Environment.NewLine, vals.ToArray()), ShortOverview = runningTime, - Severity = LogSeverity.Error + Severity = LogLevel.Error }); } } diff --git a/Emby.Server.Implementations/Activity/ActivityManager.cs b/Emby.Server.Implementations/Activity/ActivityManager.cs index 047bebf23..b0c841397 100644 --- a/Emby.Server.Implementations/Activity/ActivityManager.cs +++ b/Emby.Server.Implementations/Activity/ActivityManager.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Model.Activity; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Linq; diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs index ce9f460ff..91a4a5fd4 100644 --- a/Emby.Server.Implementations/Activity/ActivityRepository.cs +++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs @@ -6,7 +6,7 @@ using System.Linq; using Emby.Server.Implementations.Data; using MediaBrowser.Controller; using MediaBrowser.Model.Activity; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using SQLitePCL.pretty; using MediaBrowser.Model.Extensions; @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.Activity } catch (Exception ex) { - Logger.ErrorException("Error loading database file. Will reset and retry.", ex); + Logger.LogError(ex, "Error loading database file. Will reset and retry."); FileSystem.DeleteFile(DbFilePath); @@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.Activity } catch (Exception ex) { - Logger.ErrorException("Error migrating activity log database", ex); + Logger.LogError(ex, "Error migrating activity log database"); } } @@ -87,36 +87,34 @@ namespace Emby.Server.Implementations.Activity } using (WriteLock.Write()) + using (var connection = CreateConnection()) { - using (var connection = CreateConnection()) + connection.RunInTransaction(db => { - connection.RunInTransaction(db => + using (var statement = db.PrepareStatement("insert into ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)")) { - using (var statement = db.PrepareStatement("insert into ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)")) + statement.TryBind("@Name", entry.Name); + + statement.TryBind("@Overview", entry.Overview); + statement.TryBind("@ShortOverview", entry.ShortOverview); + statement.TryBind("@Type", entry.Type); + statement.TryBind("@ItemId", entry.ItemId); + + if (entry.UserId.Equals(Guid.Empty)) { - statement.TryBind("@Name", entry.Name); - - statement.TryBind("@Overview", entry.Overview); - statement.TryBind("@ShortOverview", entry.ShortOverview); - statement.TryBind("@Type", entry.Type); - statement.TryBind("@ItemId", entry.ItemId); - - if (entry.UserId.Equals(Guid.Empty)) - { - statement.TryBindNull("@UserId"); - } - else - { - statement.TryBind("@UserId", entry.UserId.ToString("N")); - } - - statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); - statement.TryBind("@LogSeverity", entry.Severity.ToString()); - - statement.MoveNext(); + statement.TryBindNull("@UserId"); } - }, TransactionMode); - } + else + { + statement.TryBind("@UserId", entry.UserId.ToString("N")); + } + + statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); + statement.TryBind("@LogSeverity", entry.Severity.ToString()); + + statement.MoveNext(); + } + }, TransactionMode); } } @@ -128,132 +126,128 @@ namespace Emby.Server.Implementations.Activity } using (WriteLock.Write()) + using (var connection = CreateConnection()) { - using (var connection = CreateConnection()) + connection.RunInTransaction(db => { - connection.RunInTransaction(db => + using (var statement = db.PrepareStatement("Update ActivityLog set Name=@Name,Overview=@Overview,ShortOverview=@ShortOverview,Type=@Type,ItemId=@ItemId,UserId=@UserId,DateCreated=@DateCreated,LogSeverity=@LogSeverity where Id=@Id")) { - using (var statement = db.PrepareStatement("Update ActivityLog set Name=@Name,Overview=@Overview,ShortOverview=@ShortOverview,Type=@Type,ItemId=@ItemId,UserId=@UserId,DateCreated=@DateCreated,LogSeverity=@LogSeverity where Id=@Id")) + statement.TryBind("@Id", entry.Id); + + statement.TryBind("@Name", entry.Name); + statement.TryBind("@Overview", entry.Overview); + statement.TryBind("@ShortOverview", entry.ShortOverview); + statement.TryBind("@Type", entry.Type); + statement.TryBind("@ItemId", entry.ItemId); + + if (entry.UserId.Equals(Guid.Empty)) { - statement.TryBind("@Id", entry.Id); - - statement.TryBind("@Name", entry.Name); - statement.TryBind("@Overview", entry.Overview); - statement.TryBind("@ShortOverview", entry.ShortOverview); - statement.TryBind("@Type", entry.Type); - statement.TryBind("@ItemId", entry.ItemId); - - if (entry.UserId.Equals(Guid.Empty)) - { - statement.TryBindNull("@UserId"); - } - else - { - statement.TryBind("@UserId", entry.UserId.ToString("N")); - } - - statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); - statement.TryBind("@LogSeverity", entry.Severity.ToString()); - - statement.MoveNext(); + statement.TryBindNull("@UserId"); } - }, TransactionMode); - } + else + { + statement.TryBind("@UserId", entry.UserId.ToString("N")); + } + + statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); + statement.TryBind("@LogSeverity", entry.Severity.ToString()); + + statement.MoveNext(); + } + }, TransactionMode); } } public QueryResult GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit) { using (WriteLock.Read()) + using (var connection = CreateConnection(true)) { - using (var connection = CreateConnection(true)) + var commandText = BaseActivitySelectText; + var whereClauses = new List(); + + if (minDate.HasValue) { - var commandText = BaseActivitySelectText; - var whereClauses = new List(); - - if (minDate.HasValue) - { - whereClauses.Add("DateCreated>=@DateCreated"); - } - if (hasUserId.HasValue) - { - if (hasUserId.Value) - { - whereClauses.Add("UserId not null"); - } - else - { - whereClauses.Add("UserId is null"); - } - } - - var whereTextWithoutPaging = whereClauses.Count == 0 ? - string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); - - if (startIndex.HasValue && startIndex.Value > 0) - { - var pagingWhereText = whereClauses.Count == 0 ? - string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); - - whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})", - pagingWhereText, - startIndex.Value.ToString(_usCulture))); - } - - var whereText = whereClauses.Count == 0 ? - string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); - - commandText += whereText; - - commandText += " ORDER BY DateCreated DESC"; - - if (limit.HasValue) - { - commandText += " LIMIT " + limit.Value.ToString(_usCulture); - } - - var statementTexts = new List(); - statementTexts.Add(commandText); - statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging); - - return connection.RunInTransaction(db => - { - var list = new List(); - var result = new QueryResult(); - - var statements = PrepareAllSafe(db, statementTexts).ToList(); - - using (var statement = statements[0]) - { - if (minDate.HasValue) - { - statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); - } - - foreach (var row in statement.ExecuteQuery()) - { - list.Add(GetEntry(row)); - } - } - - using (var statement = statements[1]) - { - if (minDate.HasValue) - { - statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); - } - - result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); - } - - result.Items = list.ToArray(list.Count); - return result; - - }, ReadTransactionMode); + whereClauses.Add("DateCreated>=@DateCreated"); } + if (hasUserId.HasValue) + { + if (hasUserId.Value) + { + whereClauses.Add("UserId not null"); + } + else + { + whereClauses.Add("UserId is null"); + } + } + + var whereTextWithoutPaging = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + if (startIndex.HasValue && startIndex.Value > 0) + { + var pagingWhereText = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})", + pagingWhereText, + startIndex.Value.ToString(_usCulture))); + } + + var whereText = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + commandText += whereText; + + commandText += " ORDER BY DateCreated DESC"; + + if (limit.HasValue) + { + commandText += " LIMIT " + limit.Value.ToString(_usCulture); + } + + var statementTexts = new List(); + statementTexts.Add(commandText); + statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging); + + return connection.RunInTransaction(db => + { + var list = new List(); + var result = new QueryResult(); + + var statements = PrepareAllSafe(db, statementTexts).ToList(); + + using (var statement = statements[0]) + { + if (minDate.HasValue) + { + statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); + } + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(GetEntry(row)); + } + } + + using (var statement = statements[1]) + { + if (minDate.HasValue) + { + statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); + } + + result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); + } + + result.Items = list.ToArray(); + return result; + + }, ReadTransactionMode); } } @@ -308,7 +302,7 @@ namespace Emby.Server.Implementations.Activity index++; if (reader[index].SQLiteType != SQLiteType.Null) { - info.Severity = (LogSeverity)Enum.Parse(typeof(LogSeverity), reader[index].ToString(), true); + info.Severity = (LogLevel)Enum.Parse(typeof(LogLevel), reader[index].ToString(), true); } return info; diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 385b4bd51..fddf19893 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -9,7 +9,7 @@ using MediaBrowser.Common.Events; using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.AppBase @@ -97,14 +97,14 @@ namespace Emby.Server.Implementations.AppBase /// Initializes a new instance of the class. /// /// The application paths. - /// The log manager. + /// The logger factory. /// The XML serializer. - protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer, IFileSystem fileSystem) + protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem) { CommonApplicationPaths = applicationPaths; XmlSerializer = xmlSerializer; FileSystem = fileSystem; - Logger = logManager.GetLogger(GetType().Name); + Logger = loggerFactory.CreateLogger(GetType().Name); UpdateCachePath(); } @@ -123,7 +123,7 @@ namespace Emby.Server.Implementations.AppBase /// public void SaveConfiguration() { - Logger.Info("Saving system configuration"); + Logger.LogInformation("Saving system configuration"); var path = CommonApplicationPaths.SystemConfigurationFilePath; FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path)); @@ -259,7 +259,7 @@ namespace Emby.Server.Implementations.AppBase } catch (Exception ex) { - Logger.ErrorException("Error loading configuration file: {0}", ex, path); + Logger.LogError(ex, "Error loading configuration file: {path}", path); return Activator.CreateInstance(configurationType); } diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index c6cfe7214..a4a24dda0 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -48,13 +48,11 @@ using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Chapters; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Connect; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; @@ -80,7 +78,6 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using MediaBrowser.Model.News; @@ -117,6 +114,7 @@ using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certif using MediaBrowser.Controller.Authentication; using System.Diagnostics; using ServiceStack.Text.Jsv; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations { @@ -202,10 +200,10 @@ namespace Emby.Server.Implementations public IPlugin[] Plugins { get; protected set; } /// - /// Gets or sets the log manager. + /// Gets or sets the logger factory. /// - /// The log manager. - public ILogManager LogManager { get; protected set; } + /// The logger factory. + public ILoggerFactory LoggerFactory { get; protected set; } /// /// Gets the application paths. @@ -275,12 +273,12 @@ namespace Emby.Server.Implementations /// IConfigurationManager. protected IConfigurationManager GetConfigurationManager() { - return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer, FileSystemManager); + return new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager); } protected virtual IResourceFileManager CreateResourceFileManager() { - return new ResourceFileManager(HttpResultFactory, LogManager.GetLogger("ResourceManager"), FileSystemManager); + return new ResourceFileManager(HttpResultFactory, LoggerFactory.CreateLogger("ResourceManager"), FileSystemManager); } /// @@ -391,7 +389,7 @@ namespace Emby.Server.Implementations /// Initializes a new instance of the class. /// public ApplicationHost(ServerApplicationPaths applicationPaths, - ILogManager logManager, + ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, @@ -405,7 +403,7 @@ namespace Emby.Server.Implementations // hack alert, until common can target .net core BaseExtensions.CryptographyProvider = CryptographyProvider; - XmlSerializer = new MyXmlSerializer(fileSystem, logManager.GetLogger("XmlSerializer")); + XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory.CreateLogger("XmlSerializer")); NetworkManager = networkManager; networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; @@ -413,13 +411,13 @@ namespace Emby.Server.Implementations SystemEvents = systemEvents; ApplicationPaths = applicationPaths; - LogManager = logManager; + LoggerFactory = loggerFactory; FileSystemManager = fileSystem; ConfigurationManager = GetConfigurationManager(); // Initialize this early in case the -v command line option is used - Logger = LogManager.GetLogger("App"); + Logger = LoggerFactory.CreateLogger("App"); StartupOptions = options; ReleaseAssetFilename = releaseAssetFilename; @@ -427,7 +425,7 @@ namespace Emby.Server.Implementations ImageEncoder = imageEncoder; - SetBaseExceptionMessage(); + //SetBaseExceptionMessage(); fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); @@ -480,7 +478,7 @@ namespace Emby.Server.Implementations { if (_deviceId == null) { - _deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId"), FileSystemManager); + _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger("SystemId"), FileSystemManager); } return _deviceId.Value; @@ -545,7 +543,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error creating {0}", ex, type.FullName); + Logger.LogError(ex, "Error creating {type}", type.FullName); // Don't blow up in release mode return null; } @@ -625,7 +623,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error loading assembly {0}", ex, file); + Logger.LogError(ex, "Error loading assembly {file}", file); return null; } } @@ -648,7 +646,7 @@ namespace Emby.Server.Implementations /// /// if set to true [manage liftime]. /// IEnumerable{``0}. - public IEnumerable GetExports(bool manageLiftime = true) + public IEnumerable GetExports(bool manageLifetime = true) { var parts = GetExportTypes() .Select(CreateInstanceSafe) @@ -656,7 +654,7 @@ namespace Emby.Server.Implementations .Cast() .ToList(); - if (manageLiftime) + if (manageLifetime) { lock (DisposableParts) { @@ -667,7 +665,7 @@ namespace Emby.Server.Implementations return parts; } - public List> GetExportsWithInfo(bool manageLiftime = true) + public List> GetExportsWithInfo(bool manageLifetime = true) { var parts = GetExportTypes() .Select(i => @@ -683,7 +681,7 @@ namespace Emby.Server.Implementations .Where(i => i != null) .ToList(); - if (manageLiftime) + if (manageLifetime) { lock (DisposableParts) { @@ -694,6 +692,8 @@ namespace Emby.Server.Implementations return parts; } + // TODO: @bond + /* private void SetBaseExceptionMessage() { var builder = GetBaseExceptionMessage(ApplicationPaths); @@ -701,8 +701,8 @@ namespace Emby.Server.Implementations builder.Insert(0, string.Format("Version: {0}{1}", ApplicationVersion, Environment.NewLine)); builder.Insert(0, "*** Error Report ***" + Environment.NewLine); - LogManager.ExceptionMessagePrefix = builder.ToString(); - } + LoggerFactory.ExceptionMessagePrefix = builder.ToString(); + }*/ /// /// Runs the startup tasks. @@ -726,20 +726,20 @@ namespace Emby.Server.Implementations // } //} - Logger.Info("ServerId: {0}", SystemId); + Logger.LogInformation("ServerId: {0}", SystemId); - var entryPoints = GetExports().ToList(); + var entryPoints = GetExports(); RunEntryPoints(entryPoints, true); - Logger.Info("Core startup complete"); + Logger.LogInformation("Core startup complete"); HttpServer.GlobalResponse = null; - Logger.Info("Post-init migrations complete"); + Logger.LogInformation("Post-init migrations complete"); RunEntryPoints(entryPoints, false); - Logger.Info("All entry points have started"); + Logger.LogInformation("All entry points have started"); - LogManager.RemoveConsoleOutput(); + //LoggerFactory.RemoveConsoleOutput(); } private void RunEntryPoints(IEnumerable entryPoints, bool isBeforeStartup) @@ -752,7 +752,7 @@ namespace Emby.Server.Implementations } var name = entryPoint.GetType().FullName; - Logger.Info("Starting entry point {0}", name); + Logger.LogInformation("Starting entry point {0}", name); var now = DateTime.UtcNow; try { @@ -760,9 +760,9 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error in {0}", ex, name); + Logger.LogError(ex, "Error in {name}", name); } - Logger.Info("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos"); + Logger.LogInformation("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos"); } } @@ -777,13 +777,13 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error configuring autorun", ex); + Logger.LogError(ex, "Error configuring autorun"); } } private IJsonSerializer CreateJsonSerializer() { - return new JsonSerializer(FileSystemManager, LogManager.GetLogger("JsonSerializer")); + return new JsonSerializer(FileSystemManager, LoggerFactory.CreateLogger("JsonSerializer")); } public void Init() @@ -801,11 +801,7 @@ namespace Emby.Server.Implementations JsonSerializer = CreateJsonSerializer(); OnLoggerLoaded(true); - LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false); - - LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging - ? LogSeverity.Debug - : LogSeverity.Info; + //LoggerFactory.LoggerLoaded += (s, e) => OnLoggerLoaded(false); DiscoverTypes(); @@ -818,7 +814,7 @@ namespace Emby.Server.Implementations protected virtual void OnLoggerLoaded(bool isFirstLoad) { - Logger.Info("Application version: {0}", ApplicationVersion); + Logger.LogInformation("Application version: {0}", ApplicationVersion); if (!isFirstLoad) { @@ -834,13 +830,13 @@ namespace Emby.Server.Implementations pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version)); } - Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder); + Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString()); } } protected virtual IHttpClient CreateHttpClient() { - return new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, GetDefaultUserAgent); + return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory.CreateLogger("HttpClient"), FileSystemManager, GetDefaultUserAgent); } public static IStreamHelper StreamHelper { get; set; } @@ -858,7 +854,7 @@ namespace Emby.Server.Implementations RegisterSingleInstance(JsonSerializer); RegisterSingleInstance(SystemEvents); - RegisterSingleInstance(LogManager, false); + RegisterSingleInstance(LoggerFactory, false); RegisterSingleInstance(Logger); RegisterSingleInstance(EnvironmentInfo); @@ -873,7 +869,7 @@ namespace Emby.Server.Implementations IsoManager = new IsoManager(); RegisterSingleInstance(IsoManager); - TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager, SystemEvents); + TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory.CreateLogger("TaskManager"), FileSystemManager, SystemEvents); RegisterSingleInstance(TaskManager); RegisterSingleInstance(XmlSerializer); @@ -890,21 +886,21 @@ namespace Emby.Server.Implementations RegisterSingleInstance(CryptographyProvider); - SocketFactory = new SocketFactory(LogManager.GetLogger("SocketFactory")); + SocketFactory = new SocketFactory(LoggerFactory.CreateLogger("SocketFactory")); RegisterSingleInstance(SocketFactory); RegisterSingleInstance(PowerManagement); - SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager, FileSystemManager, CryptographyProvider); + SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LoggerFactory, FileSystemManager, CryptographyProvider); RegisterSingleInstance(SecurityManager); - InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime); + InstallationManager = new InstallationManager(LoggerFactory.CreateLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime); RegisterSingleInstance(InstallationManager); ZipClient = new ZipClient(FileSystemManager); RegisterSingleInstance(ZipClient); - HttpResultFactory = new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer, CreateBrotliCompressor()); + HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, CreateBrotliCompressor()); RegisterSingleInstance(HttpResultFactory); RegisterSingleInstance(this); @@ -915,36 +911,36 @@ namespace Emby.Server.Implementations IAssemblyInfo assemblyInfo = new AssemblyInfo(); RegisterSingleInstance(assemblyInfo); - LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LogManager.GetLogger("LocalizationManager"), assemblyInfo, new TextLocalizer()); + LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory.CreateLogger("LocalizationManager"), assemblyInfo, new TextLocalizer()); StringExtensions.LocalizationManager = LocalizationManager; RegisterSingleInstance(LocalizationManager); - TextEncoding = new TextEncoding.TextEncoding(FileSystemManager, LogManager.GetLogger("TextEncoding"), JsonSerializer); + TextEncoding = new TextEncoding.TextEncoding(FileSystemManager, LoggerFactory.CreateLogger("TextEncoding"), JsonSerializer); RegisterSingleInstance(TextEncoding); BlurayExaminer = new BdInfoExaminer(FileSystemManager, TextEncoding); RegisterSingleInstance(BlurayExaminer); RegisterSingleInstance(new XmlReaderSettingsFactory()); - UserDataManager = new UserDataManager(LogManager, ServerConfigurationManager, () => UserManager); + UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager); RegisterSingleInstance(UserDataManager); UserRepository = GetUserRepository(); // This is only needed for disposal purposes. If removing this, make sure to have the manager handle disposing it RegisterSingleInstance(UserRepository); - var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LogManager.GetLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, FileSystemManager); + var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory.CreateLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, FileSystemManager); DisplayPreferencesRepository = displayPreferencesRepo; RegisterSingleInstance(DisplayPreferencesRepository); - var itemRepo = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LogManager.GetLogger("SqliteItemRepository"), assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory); + var itemRepo = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory.CreateLogger("SqliteItemRepository"), assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory); ItemRepository = itemRepo; RegisterSingleInstance(ItemRepository); AuthenticationRepository = GetAuthenticationRepository(); RegisterSingleInstance(AuthenticationRepository); - UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider); + UserManager = new UserManager(LoggerFactory.CreateLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider); RegisterSingleInstance(UserManager); LibraryManager = new LibraryManager(this, Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager); @@ -953,16 +949,16 @@ namespace Emby.Server.Implementations var musicManager = new MusicManager(LibraryManager); RegisterSingleInstance(new MusicManager(LibraryManager)); - LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, TimerFactory, SystemEvents, EnvironmentInfo); + LibraryMonitor = new LibraryMonitor(LoggerFactory, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, TimerFactory, SystemEvents, EnvironmentInfo); RegisterSingleInstance(LibraryMonitor); - RegisterSingleInstance(() => new SearchEngine(LogManager, LibraryManager, UserManager)); + RegisterSingleInstance(() => new SearchEngine(LoggerFactory, LibraryManager, UserManager)); CertificateInfo = GetCertificateInfo(true); Certificate = GetCertificate(CertificateInfo); HttpServer = new HttpListenerHost(this, - LogManager.GetLogger("HttpServer"), + LoggerFactory.CreateLogger("HttpServer"), ServerConfigurationManager, "web/index.html", NetworkManager, @@ -983,37 +979,37 @@ namespace Emby.Server.Implementations var encryptionManager = new EncryptionManager(); RegisterSingleInstance(encryptionManager); - DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LogManager.GetLogger("DeviceManager"), NetworkManager); + DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LoggerFactory.CreateLogger("DeviceManager"), NetworkManager); RegisterSingleInstance(DeviceManager); var newsService = new Emby.Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer); RegisterSingleInstance(newsService); - MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LogManager.GetLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder); + MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory.CreateLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder); RegisterSingleInstance(MediaSourceManager); - SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager); + SubtitleManager = new SubtitleManager(LoggerFactory.CreateLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager); RegisterSingleInstance(SubtitleManager); - ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer); + ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer); RegisterSingleInstance(ProviderManager); - DtoService = new DtoService(LogManager.GetLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager); + DtoService = new DtoService(LoggerFactory.CreateLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager); RegisterSingleInstance(DtoService); - ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LogManager.GetLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager); + ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory.CreateLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager); RegisterSingleInstance(ChannelManager); - SessionManager = new SessionManager(UserDataManager, LogManager.GetLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory); + SessionManager = new SessionManager(UserDataManager, LoggerFactory.CreateLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory); RegisterSingleInstance(SessionManager); - var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer, this, assemblyInfo); + var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory.CreateLogger("Dlna"), JsonSerializer, this, assemblyInfo); RegisterSingleInstance(dlnaManager); - CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"), ProviderManager); + CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("CollectionManager"), ProviderManager); RegisterSingleInstance(CollectionManager); - PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager, ProviderManager); + PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("PlaylistManager"), UserManager, ProviderManager); RegisterSingleInstance(PlaylistManager); LiveTvManager = new LiveTvManager(this, HttpClient, ServerConfigurationManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager, SecurityManager, () => ChannelManager); @@ -1022,12 +1018,12 @@ namespace Emby.Server.Implementations UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager); RegisterSingleInstance(UserViewManager); - NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager); + NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager); RegisterSingleInstance(NotificationManager); - RegisterSingleInstance(new DeviceDiscovery(LogManager.GetLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory)); + RegisterSingleInstance(new DeviceDiscovery(LoggerFactory.CreateLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory)); - ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository); + ChapterManager = new ChapterManager(LibraryManager, LoggerFactory.CreateLogger("ChapterManager"), ServerConfigurationManager, ItemRepository); RegisterSingleInstance(ChapterManager); RegisterMediaEncoder(assemblyInfo); @@ -1037,7 +1033,7 @@ namespace Emby.Server.Implementations var activityLogRepo = GetActivityLogRepository(); RegisterSingleInstance(activityLogRepo); - RegisterSingleInstance(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager)); + RegisterSingleInstance(new ActivityManager(LoggerFactory.CreateLogger("ActivityManager"), activityLogRepo, UserManager)); var authContext = new AuthorizationContext(AuthenticationRepository, UserManager); RegisterSingleInstance(authContext); @@ -1046,14 +1042,14 @@ namespace Emby.Server.Implementations AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager); RegisterSingleInstance(AuthService); - SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory, TextEncoding); + SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory.CreateLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory, TextEncoding); RegisterSingleInstance(SubtitleEncoder); RegisterSingleInstance(CreateResourceFileManager()); displayPreferencesRepo.Initialize(); - var userDataRepo = new SqliteUserDataRepository(LogManager.GetLogger("SqliteUserDataRepository"), ApplicationPaths, FileSystemManager); + var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger("SqliteUserDataRepository"), ApplicationPaths, FileSystemManager); SetStaticProperties(); @@ -1082,9 +1078,9 @@ namespace Emby.Server.Implementations } } - public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, bool isStartup) + public static void LogEnvironmentInfo(ILogger Logger, IApplicationPaths appPaths, bool isStartup) { - logger.LogMultiline("Emby", LogSeverity.Info, GetBaseExceptionMessage(appPaths)); + Logger.LogInformation("Jellyfin:\n{ex}", GetBaseExceptionMessage(appPaths).ToString()); } protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths) @@ -1103,17 +1099,6 @@ namespace Emby.Server.Implementations builder.AppendLine(string.Format("64-Bit OS: {0}", Environment.Is64BitOperatingSystem)); builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess)); builder.AppendLine(string.Format("User Interactive: {0}", Environment.UserInteractive)); - - Type type = Type.GetType("Mono.Runtime"); - if (type != null) - { - MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); - if (displayName != null) - { - builder.AppendLine("Mono: " + displayName.Invoke(null, null)); - } - } - builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount)); builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath)); builder.AppendLine(string.Format("Application directory: {0}", appPaths.ProgramSystemPath)); @@ -1130,7 +1115,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error setting http limit", ex); + Logger.LogError(ex, "Error setting http limit"); } } @@ -1189,7 +1174,7 @@ namespace Emby.Server.Implementations //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA; if (!localCert.HasPrivateKey) { - Logger.Error("No private key included in SSL cert {0}.", certificateLocation); + Logger.LogError("No private key included in SSL cert {0}.", certificateLocation); return null; } @@ -1197,14 +1182,14 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error loading cert from {0}", ex, certificateLocation); + Logger.LogError(ex, "Error loading cert from {certificateLocation}", certificateLocation); return null; } } private IImageProcessor GetImageProcessor() { - return new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, ImageEncoder, () => LibraryManager, TimerFactory, () => MediaEncoder); + return new ImageProcessor(LoggerFactory.CreateLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, ImageEncoder, () => LibraryManager, TimerFactory, () => MediaEncoder); } protected virtual FFMpegInstallInfo GetFfmpegInstallInfo() @@ -1262,7 +1247,8 @@ namespace Emby.Server.Implementations probePath = info.ProbePath; var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase); - var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(LogManager.GetLogger("MediaEncoder"), + var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder( + LoggerFactory.CreateLogger("MediaEncoder"), JsonSerializer, encoderPath, probePath, @@ -1292,7 +1278,7 @@ namespace Emby.Server.Implementations /// Task{IUserRepository}. private IUserRepository GetUserRepository() { - var repo = new SqliteUserRepository(LogManager.GetLogger("SqliteUserRepository"), ApplicationPaths, JsonSerializer); + var repo = new SqliteUserRepository(LoggerFactory.CreateLogger("SqliteUserRepository"), ApplicationPaths, JsonSerializer); repo.Initialize(); @@ -1301,7 +1287,7 @@ namespace Emby.Server.Implementations private IAuthenticationRepository GetAuthenticationRepository() { - var repo = new AuthenticationRepository(LogManager.GetLogger("AuthenticationRepository"), ServerConfigurationManager); + var repo = new AuthenticationRepository(LoggerFactory.CreateLogger("AuthenticationRepository"), ServerConfigurationManager); repo.Initialize(); @@ -1310,7 +1296,7 @@ namespace Emby.Server.Implementations private IActivityRepository GetActivityLogRepository() { - var repo = new ActivityRepository(LogManager.GetLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths, FileSystemManager); + var repo = new ActivityRepository(LoggerFactory.CreateLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths, FileSystemManager); repo.Initialize(); @@ -1325,7 +1311,7 @@ namespace Emby.Server.Implementations ((SqliteItemRepository)ItemRepository).ImageProcessor = ImageProcessor; // For now there's no real way to inject these properly - BaseItem.Logger = LogManager.GetLogger("BaseItem"); + BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem"); BaseItem.ConfigurationManager = ServerConfigurationManager; BaseItem.LibraryManager = LibraryManager; BaseItem.ProviderManager = ProviderManager; @@ -1425,7 +1411,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error getting plugin Id from {0}.", ex, plugin.GetType().FullName); + Logger.LogError(ex, "Error getting plugin Id from {pluginName}.", plugin.GetType().FullName); } } @@ -1437,7 +1423,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error loading plugin {0}", ex, plugin.GetType().FullName); + Logger.LogError(ex, "Error loading plugin {pluginName}", plugin.GetType().FullName); return null; } @@ -1449,7 +1435,7 @@ namespace Emby.Server.Implementations /// protected void DiscoverTypes() { - Logger.Info("Loading assemblies"); + Logger.LogInformation("Loading assemblies"); var assemblyInfos = GetComposablePartAssemblies(); @@ -1460,11 +1446,11 @@ namespace Emby.Server.Implementations if (path == null) { - Logger.Info("Loading {0}", assembly.FullName); + Logger.LogInformation("Loading {assemblyName}", assembly.FullName); } else { - Logger.Info("Loading {0} from {1}", assembly.FullName, path); + Logger.LogInformation("Loading {assemblyName} from {path}", assembly.FullName, path); } } @@ -1506,7 +1492,7 @@ namespace Emby.Server.Implementations { if (loaderException != null) { - Logger.Error("LoaderException: " + loaderException.Message); + Logger.LogError("LoaderException: " + loaderException.Message); } } } @@ -1517,7 +1503,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error loading types from assembly", ex); + Logger.LogError(ex, "Error loading types from assembly"); return new List>(); } @@ -1564,7 +1550,7 @@ namespace Emby.Server.Implementations ? "The http server is unable to start due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system." : "Error starting Http Server"; - Logger.ErrorException(msg, ex); + Logger.LogError(ex, msg); if (HttpPort == ServerConfiguration.DefaultHttpPort) { @@ -1580,7 +1566,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error starting http server", ex); + Logger.LogError(ex, "Error starting http server"); throw; } @@ -1615,7 +1601,7 @@ namespace Emby.Server.Implementations // } // catch (Exception ex) // { - // Logger.ErrorException("Error creating ssl cert", ex); + // Logger.LogError(ex, "Error creating ssl cert"); // return null; // } // } @@ -1672,7 +1658,7 @@ namespace Emby.Server.Implementations if (requiresRestart) { - Logger.Info("App needs to be restarted due to configuration change."); + Logger.LogInformation("App needs to be restarted due to configuration change."); NotifyPendingRestart(); } @@ -1683,7 +1669,7 @@ namespace Emby.Server.Implementations /// public void NotifyPendingRestart() { - Logger.Info("App needs to be restarted."); + Logger.LogInformation("App needs to be restarted."); var changed = !HasPendingRestart; @@ -1720,10 +1706,10 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error sending server restart notification", ex); + Logger.LogError(ex, "Error sending server restart notification"); } - Logger.Info("Calling RestartInternal"); + Logger.LogInformation("Calling RestartInternal"); RestartInternal(); }); @@ -1849,13 +1835,13 @@ namespace Emby.Server.Implementations { var result = Version.Parse(FileVersionInfo.GetVersionInfo(path).FileVersion); - Logger.Info("File {0} has version {1}", path, result); + Logger.LogInformation("File {0} has version {1}", path, result); return result; } catch (Exception ex) { - Logger.ErrorException("Error getting version number from {0}", ex, path); + Logger.LogError(ex, "Error getting version number from {path}", path); return new Version(1, 0); } @@ -1940,13 +1926,13 @@ namespace Emby.Server.Implementations if (version < minRequiredVersion) { - Logger.Info("Not loading {0} {1} because the minimum supported version is {2}. Please update to the newer version", filename, version, minRequiredVersion); + Logger.LogInformation("Not loading {filename} {version} because the minimum supported version is {minRequiredVersion}. Please update to the newer version", filename, version, minRequiredVersion); return false; } } catch (Exception ex) { - Logger.ErrorException("Error getting version number from {0}", ex, path); + Logger.LogError(ex, "Error getting version number from {path}", path); return false; } @@ -1962,6 +1948,7 @@ namespace Emby.Server.Implementations public async Task GetSystemInfo(CancellationToken cancellationToken) { var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false); + var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false); return new SystemInfo { @@ -1984,8 +1971,7 @@ namespace Emby.Server.Implementations CanSelfRestart = CanSelfRestart, CanSelfUpdate = CanSelfUpdate, CanLaunchWebBrowser = CanLaunchWebBrowser, - // TODO - remove WanAddress - WanAddress = "0.0.0.0", + WanAddress = wanAddress, HasUpdateAvailable = HasUpdateAvailable, SupportsAutoRunAtStartup = SupportsAutoRunAtStartup, TranscodingTempPath = ApplicationPaths.TranscodingTempPath, @@ -2012,14 +1998,13 @@ namespace Emby.Server.Implementations public async Task GetPublicSystemInfo(CancellationToken cancellationToken) { var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false); - + var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false); return new PublicSystemInfo { Version = ApplicationVersion.ToString(), Id = SystemId, OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(), - // TODO - remove WanAddress - WanAddress = "0.0.0.0", + WanAddress = wanAddress, ServerName = FriendlyName, LocalAddress = localAddress }; @@ -2054,12 +2039,38 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error getting local Ip address information", ex); + Logger.LogError(ex, "Error getting local Ip address information"); } return null; } + public async Task GetWanApiUrl(CancellationToken cancellationToken) + { + var url = "http://ipv4.icanhazip.com"; + try + { + using (var response = await HttpClient.Get(new HttpRequestOptions + { + Url = url, + LogErrorResponseBody = false, + LogErrors = false, + LogRequest = false, + TimeoutMs = 10000, + BufferContent = false, + CancellationToken = cancellationToken + })) + { + return GetLocalApiUrl(response.ReadToEnd().Trim()); + } + } + catch(Exception ex) + { + Logger.LogError(ex, "Error getting WAN Ip address information"); + } + return null; + } + public string GetLocalApiUrl(IpAddressInfo ipAddress) { if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6) @@ -2185,19 +2196,19 @@ namespace Emby.Server.Implementations var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase); _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid); - Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, valid); + Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid); return valid; } } } catch (OperationCanceledException) { - Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled"); + Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled"); throw; } catch (Exception ex) { - Logger.Debug("Ping test result to {0}. Success: {1} {2}", apiUrl, false, ex.Message); + Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false); _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false); return false; @@ -2236,7 +2247,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error sending server shutdown notification", ex); + Logger.LogError(ex, "Error sending server shutdown notification"); } ShutdownInternal(); @@ -2249,7 +2260,7 @@ namespace Emby.Server.Implementations /// private void RegisterServerWithAdministratorAccess() { - Logger.Info("Requesting administrative access to authorize http server"); + Logger.LogInformation("Requesting administrative access to authorize http server"); try { @@ -2261,7 +2272,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error authorizing server", ex); + Logger.LogError(ex, "Error authorizing server"); } } @@ -2428,9 +2439,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Console.WriteLine("Error launching url: {0}", url); - Logger.ErrorException("Error launching url: {0}", ex, url); - + Logger.LogError(ex, "Error launching url: {url}", url); throw; } } @@ -2450,7 +2459,7 @@ namespace Emby.Server.Implementations /// The package. protected void OnApplicationUpdated(PackageVersionInfo package) { - Logger.Info("Application has been updated to version {0}", package.versionStr); + Logger.LogInformation("Application has been updated to version {0}", package.versionStr); EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs { @@ -2485,15 +2494,15 @@ namespace Emby.Server.Implementations { var type = GetType(); - LogManager.AddConsoleOutput(); - Logger.Info("Disposing " + type.Name); + //LoggerFactory.AddConsoleOutput(); + Logger.LogInformation("Disposing " + type.Name); var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList(); DisposableParts.Clear(); foreach (var part in parts) { - Logger.Info("Disposing " + part.GetType().Name); + Logger.LogInformation("Disposing " + part.GetType().Name); try { @@ -2501,7 +2510,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name); + Logger.LogError(ex, "Error disposing {0}", part.GetType().Name); } } } diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index e61c5e283..00da46f30 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -10,7 +10,7 @@ using MediaBrowser.Model.Channels; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using MediaBrowser.Model.Querying; @@ -239,7 +239,7 @@ namespace Emby.Server.Implementations.Channels all = all.Take(query.Limit.Value).ToList(); } - var returnItems = all.ToArray(all.Count); + var returnItems = all.ToArray(); if (query.RefreshLatestChannelItems) { @@ -300,7 +300,7 @@ namespace Emby.Server.Implementations.Channels } catch (Exception ex) { - _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Name); + _logger.LogError(ex, "Error getting channel information for {0}", channelInfo.Name); } numComplete++; @@ -484,10 +484,9 @@ namespace Emby.Server.Implementations.Channels _libraryManager.CreateItem(item, null); } - await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) + await item.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = !isNew && forceUpdate - }, cancellationToken); return item; @@ -709,7 +708,7 @@ namespace Emby.Server.Implementations.Channels // Not yet sure why this is causing a problem query.GroupByPresentationUniqueKey = false; - //_logger.Debug("GetChannelItemsInternal"); + //_logger.LogDebug("GetChannelItemsInternal"); // null if came from cache if (itemsResult != null) @@ -849,7 +848,7 @@ namespace Emby.Server.Implementations.Channels } catch (Exception ex) { - _logger.ErrorException("Error writing to channel cache file: {0}", ex, path); + _logger.LogError(ex, "Error writing to channel cache file: {path}", path); } } @@ -912,7 +911,7 @@ namespace Emby.Server.Implementations.Channels } catch (Exception ex) { - _logger.ErrorException("Error retrieving channel item from database", ex); + _logger.LogError(ex, "Error retrieving channel item from database"); } if (item == null) @@ -1011,7 +1010,7 @@ namespace Emby.Server.Implementations.Channels { item.Name = info.Name; item.Genres = info.Genres.ToArray(); - item.Studios = info.Studios.ToArray(info.Studios.Count); + item.Studios = info.Studios.ToArray(); item.CommunityRating = info.CommunityRating; item.Overview = info.Overview; item.IndexNumber = info.IndexNumber; @@ -1021,7 +1020,7 @@ namespace Emby.Server.Implementations.Channels item.ProviderIds = info.ProviderIds; item.OfficialRating = info.OfficialRating; item.DateCreated = info.DateCreated ?? DateTime.UtcNow; - item.Tags = info.Tags.ToArray(info.Tags.Count); + item.Tags = info.Tags.ToArray(); item.OriginalTitle = info.OriginalTitle; } else if (info.Type == ChannelItemType.Folder && info.FolderType == ChannelFolderType.Container) @@ -1043,7 +1042,7 @@ namespace Emby.Server.Implementations.Channels var hasAlbumArtists = item as IHasAlbumArtist; if (hasAlbumArtists != null) { - hasAlbumArtists.AlbumArtists = info.AlbumArtists.ToArray(info.AlbumArtists.Count); + hasAlbumArtists.AlbumArtists = info.AlbumArtists.ToArray(); } var trailer = item as Trailer; @@ -1051,7 +1050,7 @@ namespace Emby.Server.Implementations.Channels { if (!info.TrailerTypes.SequenceEqual(trailer.TrailerTypes)) { - _logger.Debug("Forcing update due to TrailerTypes {0}", item.Name); + _logger.LogDebug("Forcing update due to TrailerTypes {0}", item.Name); forceUpdate = true; } trailer.TrailerTypes = info.TrailerTypes.ToArray(); @@ -1060,7 +1059,7 @@ namespace Emby.Server.Implementations.Channels if (info.DateModified > item.DateModified) { item.DateModified = info.DateModified; - _logger.Debug("Forcing update due to DateModified {0}", item.Name); + _logger.LogDebug("Forcing update due to DateModified {0}", item.Name); forceUpdate = true; } @@ -1069,20 +1068,20 @@ namespace Emby.Server.Implementations.Channels //{ // item.ExternalEtag = info.Etag; // forceUpdate = true; - // _logger.Debug("Forcing update due to ExternalEtag {0}", item.Name); + // _logger.LogDebug("Forcing update due to ExternalEtag {0}", item.Name); //} if (!internalChannelId.Equals(item.ChannelId)) { forceUpdate = true; - _logger.Debug("Forcing update due to ChannelId {0}", item.Name); + _logger.LogDebug("Forcing update due to ChannelId {0}", item.Name); } item.ChannelId = internalChannelId; if (!item.ParentId.Equals(parentFolderId)) { forceUpdate = true; - _logger.Debug("Forcing update due to parent folder Id {0}", item.Name); + _logger.LogDebug("Forcing update due to parent folder Id {0}", item.Name); } item.ParentId = parentFolderId; @@ -1092,7 +1091,7 @@ namespace Emby.Server.Implementations.Channels if (!string.Equals(hasSeries.SeriesName, info.SeriesName, StringComparison.OrdinalIgnoreCase)) { forceUpdate = true; - _logger.Debug("Forcing update due to SeriesName {0}", item.Name); + _logger.LogDebug("Forcing update due to SeriesName {0}", item.Name); } hasSeries.SeriesName = info.SeriesName; } @@ -1100,7 +1099,7 @@ namespace Emby.Server.Implementations.Channels if (!string.Equals(item.ExternalId, info.Id, StringComparison.OrdinalIgnoreCase)) { forceUpdate = true; - _logger.Debug("Forcing update due to ExternalId {0}", item.Name); + _logger.LogDebug("Forcing update due to ExternalId {0}", item.Name); } item.ExternalId = info.Id; @@ -1125,7 +1124,7 @@ namespace Emby.Server.Implementations.Channels if (!string.IsNullOrEmpty(info.ImageUrl) && !item.HasImage(ImageType.Primary)) { item.SetImagePath(ImageType.Primary, info.ImageUrl); - _logger.Debug("Forcing update due to ImageUrl {0}", item.Name); + _logger.LogDebug("Forcing update due to ImageUrl {0}", item.Name); forceUpdate = true; } @@ -1134,7 +1133,7 @@ namespace Emby.Server.Implementations.Channels if (item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase)) { item.Tags = item.Tags.Except(new[] { "livestream" }, StringComparer.OrdinalIgnoreCase).ToArray(); - _logger.Debug("Forcing update due to Tags {0}", item.Name); + _logger.LogDebug("Forcing update due to Tags {0}", item.Name); forceUpdate = true; } } @@ -1143,7 +1142,7 @@ namespace Emby.Server.Implementations.Channels if (!item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase)) { item.Tags = item.Tags.Concat(new[] { "livestream" }).ToArray(); - _logger.Debug("Forcing update due to Tags {0}", item.Name); + _logger.LogDebug("Forcing update due to Tags {0}", item.Name); forceUpdate = true; } } @@ -1178,7 +1177,7 @@ namespace Emby.Server.Implementations.Channels if (isNew || forceUpdate || item.DateLastRefreshed == default(DateTime)) { - _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.Normal); + _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal); } return item; diff --git a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs index b211908d8..bd717bc6a 100644 --- a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs +++ b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.Channels private void CleanChannel(Guid id, CancellationToken cancellationToken) { - _logger.Info("Cleaning channel {0} from database", id); + _logger.LogInformation("Cleaning channel {0} from database", id); // Delete all channel items var allIds = _libraryManager.GetItemIds(new InternalItemsQuery diff --git a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs index 020818361..ab6acf3c5 100644 --- a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs +++ b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs @@ -1,8 +1,9 @@ using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Progress; using MediaBrowser.Model.Tasks; @@ -54,7 +55,7 @@ namespace Emby.Server.Implementations.Channels get { return true; } } - public async Task Execute(System.Threading.CancellationToken cancellationToken, IProgress progress) + public async Task Execute(CancellationToken cancellationToken, IProgress progress) { var manager = (ChannelManager)_channelManager; diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 675a726e5..d1afb0712 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -143,7 +143,7 @@ namespace Emby.Server.Implementations.Collections if (options.ItemIdList.Length > 0) { - AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(_fileSystem) + AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { // The initial adding of items is going to create a local metadata file // This will cause internet metadata to be skipped as a result @@ -152,7 +152,7 @@ namespace Emby.Server.Implementations.Collections } else { - _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.High); + _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.High); } EventHelper.FireEventIfNotNull(CollectionCreated, this, new CollectionCreatedEventArgs @@ -173,12 +173,12 @@ namespace Emby.Server.Implementations.Collections public void AddToCollection(Guid collectionId, IEnumerable ids) { - AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(_fileSystem)); + AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))); } public void AddToCollection(Guid collectionId, IEnumerable ids) { - AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(_fileSystem)); + AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))); } private void AddToCollection(Guid collectionId, IEnumerable ids, bool fireEvent, MetadataRefreshOptions refreshOptions) @@ -219,7 +219,7 @@ namespace Emby.Server.Implementations.Collections { var newList = collection.LinkedChildren.ToList(); newList.AddRange(list); - collection.LinkedChildren = newList.ToArray(newList.Count); + collection.LinkedChildren = newList.ToArray(); collection.UpdateRatingToItems(linkedChildrenList); @@ -265,7 +265,7 @@ namespace Emby.Server.Implementations.Collections if (child == null) { - _logger.Warn("No collection title exists with the supplied Id"); + _logger.LogWarning("No collection title exists with the supplied Id"); continue; } @@ -283,7 +283,7 @@ namespace Emby.Server.Implementations.Collections } collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None); - _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true }, RefreshPriority.High); @@ -365,7 +365,7 @@ namespace Emby.Server.Implementations.Collections } catch (Exception ex) { - _logger.ErrorException("Error creating camera uploads library", ex); + _logger.LogError(ex, "Error creating camera uploads library"); } _config.Configuration.CollectionsUpgraded = true; diff --git a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs index 47e2ec0a8..26a7c421f 100644 --- a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs +++ b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs @@ -14,7 +14,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Events; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Extensions; @@ -30,11 +30,11 @@ namespace Emby.Server.Implementations.Configuration /// Initializes a new instance of the class. /// /// The application paths. - /// The log manager. + /// The paramref name="loggerFactory" factory. /// The XML serializer. /// The file system. - public ServerConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer, IFileSystem fileSystem) - : base(applicationPaths, logManager, xmlSerializer, fileSystem) + public ServerConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem) + : base(applicationPaths, loggerFactory, xmlSerializer, fileSystem) { UpdateMetadataPath(); } diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs index 76ebff3a8..59776c373 100644 --- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs +++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using SQLitePCL.pretty; using System.Linq; using SQLitePCL; @@ -75,22 +75,22 @@ namespace Emby.Server.Implementations.Data if (!_versionLogged) { _versionLogged = true; - Logger.Info("Sqlite version: " + SQLite3.Version); - Logger.Info("Sqlite compiler options: " + string.Join(",", SQLite3.CompilerOptions.ToArray())); + Logger.LogInformation("Sqlite version: " + SQLite3.Version); + Logger.LogInformation("Sqlite compiler options: " + string.Join(",", SQLite3.CompilerOptions.ToArray())); } ConnectionFlags connectionFlags; if (isReadOnly) { - //Logger.Info("Opening read connection"); + //Logger.LogInformation("Opening read connection"); //connectionFlags = ConnectionFlags.ReadOnly; connectionFlags = ConnectionFlags.Create; connectionFlags |= ConnectionFlags.ReadWrite; } else { - //Logger.Info("Opening write connection"); + //Logger.LogInformation("Opening write connection"); connectionFlags = ConnectionFlags.Create; connectionFlags |= ConnectionFlags.ReadWrite; } @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.Data { _defaultWal = db.Query("PRAGMA journal_mode").SelectScalarString().First(); - Logger.Info("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal); + Logger.LogInformation("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal); } var queries = new List @@ -235,7 +235,7 @@ namespace Emby.Server.Implementations.Data } db.ExecuteAll(string.Join(";", queries.ToArray())); - Logger.Info("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First()); + Logger.LogInformation("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First()); } protected virtual bool EnableTempStoreMemory @@ -323,7 +323,7 @@ namespace Emby.Server.Implementations.Data } catch (Exception ex) { - Logger.ErrorException("Error disposing database", ex); + Logger.LogError(ex, "Error disposing database"); } } diff --git a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs index 8611cabc1..536cf21f6 100644 --- a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs +++ b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -47,7 +47,7 @@ namespace Emby.Server.Implementations.Data var numComplete = 0; var numItems = itemIds.Count; - _logger.Debug("Cleaning {0} items with dead parent links", numItems); + _logger.LogDebug("Cleaning {0} items with dead parent links", numItems); foreach (var itemId in itemIds) { @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Data if (item != null) { - _logger.Info("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty); + _logger.LogInformation("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty); _libraryManager.DeleteItem(item, new DeleteOptions { @@ -75,4 +75,4 @@ namespace Emby.Server.Implementations.Data progress.Report(100); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs index 09ff7e09d..00e1956cf 100644 --- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs @@ -7,7 +7,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using SQLitePCL.pretty; @@ -53,7 +53,7 @@ namespace Emby.Server.Implementations.Data } catch (Exception ex) { - Logger.ErrorException("Error loading database file. Will reset and retry.", ex); + Logger.LogError(ex, "Error loading database file. Will reset and retry."); FileSystem.DeleteFile(DbFilePath); @@ -251,4 +251,4 @@ namespace Emby.Server.Implementations.Data return GetDisplayPreferences(displayPreferencesId, new Guid(userId), client); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index c9495c574..0f9770e8f 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -24,7 +24,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Reflection; @@ -667,7 +667,7 @@ namespace Emby.Server.Implementations.Data var userDataKey = tuple.Item4; SaveItem(item, topParent, userDataKey, saveItemStatement); - //Logger.Debug(_saveItemCommand.CommandText); + //logger.LogDebug(_saveItemCommand.CommandText); var inheritedTags = tuple.Item5; @@ -886,12 +886,12 @@ namespace Emby.Server.Implementations.Data if (topParent != null) { - //Logger.Debug("Item {0} has top parent {1}", item.Id, topParent.Id); + //logger.LogDebug("Item {0} has top parent {1}", item.Id, topParent.Id); saveItemStatement.TryBind("@TopParentId", topParent.Id.ToString("N")); } else { - //Logger.Debug("Item {0} has null top parent", item.Id); + //logger.LogDebug("Item {0} has null top parent", item.Id); saveItemStatement.TryBindNull("@TopParentId"); } @@ -1148,7 +1148,7 @@ namespace Emby.Server.Implementations.Data } } - item.ImageInfos = list.ToArray(list.Count); + item.ImageInfos = list.ToArray(); } public string ToValueString(ItemImageInfo image) @@ -1230,7 +1230,7 @@ namespace Emby.Server.Implementations.Data } CheckDisposed(); - //Logger.Info("Retrieving item {0}", id.ToString("N")); + //logger.LogInformation("Retrieving item {0}", id.ToString("N")); using (WriteLock.Read()) { using (var connection = CreateConnection(true)) @@ -1345,7 +1345,7 @@ namespace Emby.Server.Implementations.Data if (type == null) { - //Logger.Debug("Unknown type {0}", typeString); + //logger.LogDebug("Unknown type {0}", typeString); return null; } @@ -1364,7 +1364,7 @@ namespace Emby.Server.Implementations.Data } catch (SerializationException ex) { - Logger.ErrorException("Error deserializing item", ex); + Logger.LogError(ex, "Error deserializing item"); } } } @@ -2566,7 +2566,7 @@ namespace Emby.Server.Implementations.Data excludeIds.Add(item.Id); excludeIds.AddRange(item.ExtraIds); - query.ExcludeItemIds = excludeIds.ToArray(excludeIds.Count); + query.ExcludeItemIds = excludeIds.ToArray(); query.ExcludeProviderIds = item.ProviderIds; } @@ -2587,7 +2587,7 @@ namespace Emby.Server.Implementations.Data list.Add(builder.ToString()); } - return list.ToArray(list.Count); + return list.ToArray(); } private void BindSearchParams(InternalItemsQuery query, IStatement statement) @@ -2666,7 +2666,7 @@ namespace Emby.Server.Implementations.Data if (groups.Count > 0) { - return " Group by " + string.Join(",", groups.ToArray(groups.Count)); + return " Group by " + string.Join(",", groups.ToArray()); } return string.Empty; @@ -2686,7 +2686,7 @@ namespace Emby.Server.Implementations.Data CheckDisposed(); - //Logger.Info("GetItemList: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemList: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -2703,7 +2703,7 @@ namespace Emby.Server.Implementations.Data var whereText = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); + " where " + string.Join(" AND ", whereClauses.ToArray()); commandText += whereText; @@ -2744,7 +2744,7 @@ namespace Emby.Server.Implementations.Data CheckDisposed(); - //Logger.Info("GetItemList: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemList: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -2761,7 +2761,7 @@ namespace Emby.Server.Implementations.Data var whereText = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); + " where " + string.Join(" AND ", whereClauses.ToArray()); commandText += whereText; @@ -2910,14 +2910,14 @@ namespace Emby.Server.Implementations.Data if (elapsed >= slowThreshold) { - Logger.Debug("{2} query time (slow): {0}ms. Query: {1}", + Logger.LogDebug("{2} query time (slow): {0}ms. Query: {1}", Convert.ToInt32(elapsed), commandText, methodName); } else { - //Logger.Debug("{2} query time: {0}ms. Query: {1}", + //logger.LogDebug("{2} query time: {0}ms. Query: {1}", // Convert.ToInt32(elapsed), // commandText, // methodName); @@ -2938,11 +2938,11 @@ namespace Emby.Server.Implementations.Data var returnList = GetItemList(query); return new QueryResult { - Items = returnList.ToArray(returnList.Count), + Items = returnList.ToArray(), TotalRecordCount = returnList.Count }; } - //Logger.Info("GetItems: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItems: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -2961,7 +2961,7 @@ namespace Emby.Server.Implementations.Data var whereText = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); + " where " + string.Join(" AND ", whereClauses.ToArray()); var whereTextWithoutPaging = whereText; @@ -3079,7 +3079,7 @@ namespace Emby.Server.Implementations.Data LogQueryTime("GetItems", commandText, now); - result.Items = list.ToArray(list.Count); + result.Items = list.ToArray(); return result; }, ReadTransactionMode); @@ -3216,7 +3216,7 @@ namespace Emby.Server.Implementations.Data } CheckDisposed(); - //Logger.Info("GetItemIdsList: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemIdsList: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -3227,7 +3227,7 @@ namespace Emby.Server.Implementations.Data var whereText = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); + " where " + string.Join(" AND ", whereClauses.ToArray()); commandText += whereText; @@ -3299,7 +3299,7 @@ namespace Emby.Server.Implementations.Data var whereText = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); + " where " + string.Join(" AND ", whereClauses.ToArray()); commandText += whereText; @@ -3372,11 +3372,11 @@ namespace Emby.Server.Implementations.Data var returnList = GetItemIdsList(query); return new QueryResult { - Items = returnList.ToArray(returnList.Count), + Items = returnList.ToArray(), TotalRecordCount = returnList.Count }; } - //Logger.Info("GetItemIds: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemIds: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -3387,7 +3387,7 @@ namespace Emby.Server.Implementations.Data var whereText = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); + " where " + string.Join(" AND ", whereClauses.ToArray()); var whereTextWithoutPaging = whereText; @@ -3495,7 +3495,7 @@ namespace Emby.Server.Implementations.Data LogQueryTime("GetItemIds", commandText, now); - result.Items = list.ToArray(list.Count); + result.Items = list.ToArray(); return result; }, ReadTransactionMode); @@ -3690,7 +3690,7 @@ namespace Emby.Server.Implementations.Data statement.TryBind("@IsMovie", true); } - whereClauses.Add("(" + string.Join(" OR ", programAttribtues.ToArray(programAttribtues.Count)) + ")"); + whereClauses.Add("(" + string.Join(" OR ", programAttribtues.ToArray()) + ")"); } else if (query.IsMovie.HasValue) { @@ -5565,7 +5565,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type } CheckDisposed(); - //Logger.Info("GetItemValues: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemValues: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -5734,7 +5734,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type var list = new List>(); var result = new QueryResult>(); - //Logger.Info("GetItemValues {0}", string.Join(";", statementTexts.ToArray())); + //logger.LogInformation("GetItemValues {0}", string.Join(";", statementTexts.ToArray())); var statements = PrepareAllSafe(db, statementTexts); if (!isReturningZeroItems) @@ -5813,7 +5813,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { result.TotalRecordCount = list.Count; } - result.Items = list.ToArray(list.Count); + result.Items = list.ToArray(); return result; diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index 07d64a2b0..6d4ddcedd 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -7,7 +7,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using SQLitePCL.pretty; using MediaBrowser.Controller.Library; @@ -416,4 +416,4 @@ namespace Emby.Server.Implementations.Data // handled by library database } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs index da828aa11..d490a481e 100644 --- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using SQLitePCL.pretty; @@ -74,7 +74,7 @@ namespace Emby.Server.Implementations.Data } catch (Exception ex) { - Logger.ErrorException("Error migrating users database", ex); + Logger.LogError(ex, "Error migrating users database"); } } @@ -233,4 +233,4 @@ namespace Emby.Server.Implementations.Data } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs index 5e0323ddb..90cef5d06 100644 --- a/Emby.Server.Implementations/Devices/DeviceId.cs +++ b/Emby.Server.Implementations/Devices/DeviceId.cs @@ -3,7 +3,7 @@ using System.IO; using System.Text; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Devices { @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.Devices return value; } - _logger.Error("Invalid value found in device id file"); + _logger.LogError("Invalid value found in device id file"); } } catch (DirectoryNotFoundException) @@ -45,7 +45,7 @@ namespace Emby.Server.Implementations.Devices } catch (Exception ex) { - _logger.ErrorException("Error reading file", ex); + _logger.LogError(ex, "Error reading file"); } return null; @@ -66,7 +66,7 @@ namespace Emby.Server.Implementations.Devices } catch (Exception ex) { - _logger.ErrorException("Error writing to file", ex); + _logger.LogError(ex, "Error writing to file"); } } diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index 0fac886ef..250316211 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Model.Devices; using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Session; @@ -289,7 +289,7 @@ namespace Emby.Server.Implementations.Devices var list = history.FilesUploaded.ToList(); list.Add(file); - history.FilesUploaded = list.ToArray(list.Count); + history.FilesUploaded = list.ToArray(); _json.SerializeToFile(history, path); } @@ -434,7 +434,7 @@ namespace Emby.Server.Implementations.Devices } catch (Exception ex) { - _logger.ErrorException("Error creating camera uploads library", ex); + _logger.LogError(ex, "Error creating camera uploads library"); } _config.Configuration.CameraUploadUpgraded = true; @@ -501,4 +501,4 @@ namespace Emby.Server.Implementations.Devices return config.GetConfiguration("devices"); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 437917c45..7871d3fb3 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -16,7 +16,7 @@ using MediaBrowser.Controller.Sync; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; @@ -225,7 +225,7 @@ namespace Emby.Server.Implementations.Dto catch (Exception ex) { // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions - _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name); + _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {itemName}", item.Name); } } @@ -547,7 +547,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.ErrorException("Error getting {0} image info", ex, type); + _logger.LogError(ex, "Error getting {type} image info", type); return null; } } @@ -560,7 +560,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path); + _logger.LogError(ex, "Error getting {imageType} image info for {path}", image.Type, image.Path); return null; } } @@ -619,7 +619,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.ErrorException("Error getting person {0}", ex, c); + _logger.LogError(ex, "Error getting person {Name}", c); return null; } @@ -648,7 +648,7 @@ namespace Emby.Server.Implementations.Dto } } - dto.People = list.ToArray(list.Count); + dto.People = list.ToArray(); } /// @@ -1451,7 +1451,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - //_logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, imageInfo.Path); + _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path); return null; } } @@ -1464,7 +1464,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name); + _logger.LogError(ex, "Error in image enhancer: {0}", enhancer.GetType().Name); } } diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index bf459defb..241505019 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -38,7 +38,7 @@ false - + @@ -46,6 +46,6 @@ - + diff --git a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs index 561f5ee12..a0947c87d 100644 --- a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; using System; using System.Linq; @@ -65,7 +65,7 @@ namespace Emby.Server.Implementations.EntryPoints { DisposeTimer(); - _logger.Info("Automatically restarting the system because it is idle and a restart is required."); + _logger.LogInformation("Automatically restarting the system because it is idle and a restart is required."); try { @@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error restarting server", ex); + _logger.LogError(ex, "Error restarting server"); } } } @@ -98,7 +98,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error getting timers", ex); + _logger.LogError(ex, "Error getting timers"); } } diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index 6801b2823..6cd867921 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -9,10 +9,9 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Threading; using Mono.Nat; -using MediaBrowser.Model.Extensions; using System.Threading; namespace Emby.Server.Implementations.EntryPoints @@ -30,9 +29,9 @@ namespace Emby.Server.Implementations.EntryPoints private NatManager _natManager; - public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, ITimerFactory timerFactory) + public ExternalPortForwarding(ILoggerFactory loggerFactory, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, ITimerFactory timerFactory) { - _logger = logmanager.GetLogger("PortMapper"); + _logger = loggerFactory.CreateLogger("PortMapper"); _appHost = appHost; _config = config; _deviceDiscovery = deviceDiscovery; @@ -59,7 +58,7 @@ namespace Emby.Server.Implementations.EntryPoints values.Add(_appHost.EnableHttps.ToString()); values.Add((config.EnableRemoteAccess).ToString()); - return string.Join("|", values.ToArray(values.Count)); + return string.Join("|", values.ToArray()); } void _config_ConfigurationUpdated(object sender, EventArgs e) @@ -85,7 +84,7 @@ namespace Emby.Server.Implementations.EntryPoints private void Start() { - _logger.Debug("Starting NAT discovery"); + _logger.LogDebug("Starting NAT discovery"); if (_natManager == null) { _natManager = new NatManager(_logger, _httpClient); @@ -140,7 +139,7 @@ namespace Emby.Server.Implementations.EntryPoints _usnsHandled.Add(identifier); } - _logger.Debug("Found NAT device: " + identifier); + _logger.LogDebug("Found NAT device: " + identifier); IPAddress address; if (IPAddress.TryParse(info.Location.Host, out address)) @@ -167,6 +166,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { + _logger.LogError(ex, "Error"); return; } @@ -217,7 +217,7 @@ namespace Emby.Server.Implementations.EntryPoints catch { // Commenting out because users are reporting problems out of our control - //_logger.ErrorException("Error creating port forwarding rules", ex); + //_logger.LogError(ex, "Error creating port forwarding rules"); } } @@ -254,6 +254,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { + _logger.LogError(ex, "Error creating http port map"); return; } @@ -263,12 +264,13 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { + _logger.LogError(ex, "Error creating https port map"); } } private Task CreatePortMap(INatDevice device, int privatePort, int publicPort) { - _logger.Debug("Creating port map on local port {0} to public port {1} with device {2}", privatePort, publicPort, device.LocalAddress.ToString()); + _logger.LogDebug("Creating port map on local port {0} to public port {1} with device {2}", privatePort, publicPort, device.LocalAddress.ToString()); return device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort) { @@ -285,7 +287,7 @@ namespace Emby.Server.Implementations.EntryPoints private void DisposeNat() { - _logger.Debug("Stopping NAT discovery"); + _logger.LogDebug("Stopping NAT discovery"); if (_timer != null) { @@ -310,10 +312,10 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error stopping NAT Discovery", ex); + _logger.LogError(ex, "Error stopping NAT Discovery"); } } } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs b/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs index 8ae85e390..a6dadcef0 100644 --- a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs +++ b/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using MediaBrowser.Model.System; @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error resetting system standby timer", ex); + _logger.LogError(ex, "Error resetting system standby timer"); } } diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs index 9a2ae34bc..bb8ef52f1 100644 --- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -331,7 +331,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error in GetLibraryUpdateInfo", ex); + _logger.LogError(ex, "Error in GetLibraryUpdateInfo"); return; } @@ -346,7 +346,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error sending LibraryChanged message", ex); + _logger.LogError(ex, "Error sending LibraryChanged message"); } } } diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs index d41d76c6b..0b377dc68 100644 --- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { @@ -66,7 +66,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError(ex, "Error sending message"); } } diff --git a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs index 4c16b1d39..660ca3a94 100644 --- a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs +++ b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Threading.Tasks; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { @@ -15,10 +16,12 @@ namespace Emby.Server.Implementations.EntryPoints /// public class RefreshUsersMetadata : IScheduledTask, IConfigurableScheduledTask { + private readonly ILogger _logger; /// /// The _user manager /// private readonly IUserManager _userManager; + private IFileSystem _fileSystem; public string Name => "Refresh Users"; @@ -41,8 +44,9 @@ namespace Emby.Server.Implementations.EntryPoints /// /// Initializes a new instance of the class. /// - public RefreshUsersMetadata(IUserManager userManager, IFileSystem fileSystem) + public RefreshUsersMetadata(ILogger logger, IUserManager userManager, IFileSystem fileSystem) { + _logger = logger; _userManager = userManager; _fileSystem = fileSystem; } @@ -55,7 +59,7 @@ namespace Emby.Server.Implementations.EntryPoints { cancellationToken.ThrowIfCancellationRequested(); - await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); } } diff --git a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs index e5748989e..72dcabab3 100644 --- a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs @@ -156,14 +156,10 @@ namespace Emby.Server.Implementations.EntryPoints try { await _sessionManager.SendMessageToAdminSessions(name, data, CancellationToken.None); - } - catch (ObjectDisposedException) - { - } catch (Exception) { - //Logger.ErrorException("Error sending message", ex); + } } @@ -172,14 +168,10 @@ namespace Emby.Server.Implementations.EntryPoints try { await _sessionManager.SendMessageToUserSessions(new List { user.Id }, name, data, CancellationToken.None); - } - catch (ObjectDisposedException) - { - } catch (Exception) { - //Logger.ErrorException("Error sending message", ex); + } } diff --git a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs index 6d73f98ad..ffd98bf78 100644 --- a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs +++ b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs @@ -1,7 +1,7 @@ using Emby.Server.Implementations.Browser; using MediaBrowser.Controller; using MediaBrowser.Controller.Plugins; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Controller.Configuration; namespace Emby.Server.Implementations.EntryPoints @@ -61,4 +61,4 @@ namespace Emby.Server.Implementations.EntryPoints { } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 5edc5fade..730ced055 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,7 +1,7 @@ using System; using MediaBrowser.Controller; using MediaBrowser.Controller.Plugins; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using Emby.Server.Implementations.Udp; using MediaBrowser.Model.Net; @@ -45,9 +45,6 @@ namespace Emby.Server.Implementations.EntryPoints /// public void Run() { - // ToDo: Fix This - return; - var udpServer = new UdpServer(_logger, _appHost, _json, _socketFactory); try @@ -58,7 +55,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Failed to start UDP Server", ex); + _logger.LogError(ex, "Failed to start UDP Server"); } } diff --git a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs index 97feb32c0..f7542a5e9 100644 --- a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs @@ -3,7 +3,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.EntryPoints session.ApplicationVersion }; - var key = string.Join("_", keys.ToArray(keys.Count)).GetMD5(); + var key = string.Join("_", keys.ToArray()).GetMD5(); ClientInfo info; if (!_apps.TryGetValue(key, out info)) @@ -91,7 +91,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - //_logger.ErrorException("Error sending anonymous usage statistics.", ex); + _logger.LogError(ex, "Error sending anonymous usage statistics."); } } @@ -119,7 +119,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - //_logger.ErrorException("Error sending anonymous usage statistics.", ex); + _logger.LogError(ex, "Error sending anonymous usage statistics."); } } diff --git a/Emby.Server.Implementations/EntryPoints/UsageReporter.cs b/Emby.Server.Implementations/EntryPoints/UsageReporter.cs index d9c9e1a40..e962bb59b 100644 --- a/Emby.Server.Implementations/EntryPoints/UsageReporter.cs +++ b/Emby.Server.Implementations/EntryPoints/UsageReporter.cs @@ -9,7 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { @@ -75,7 +75,7 @@ namespace Emby.Server.Implementations.EntryPoints throw new ArgumentException("Client info must have a device Id"); } - _logger.Info("App Activity: app: {0}, version: {1}, deviceId: {2}, deviceName: {3}", + _logger.LogInformation("App Activity: app: {0}, version: {1}, deviceId: {2}, deviceName: {3}", app.AppName ?? "Unknown App", app.AppVersion ?? "Unknown", app.DeviceId, diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs index 36e29e46a..58309ea1c 100644 --- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Session; using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs index 583e93706..765505109 100644 --- a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs +++ b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs @@ -92,4 +92,4 @@ namespace Emby.Server.Implementations.EnvironmentInfo Environment.SetEnvironmentVariable(name, value); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs b/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs index fe1df0953..5f043e127 100644 --- a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs +++ b/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index d53606e87..23dd55b18 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -14,7 +14,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Controller.IO; @@ -131,7 +131,7 @@ namespace Emby.Server.Implementations.HttpClientManager var userInfo = uriAddress.UserInfo; if (!string.IsNullOrWhiteSpace(userInfo)) { - _logger.Info("Found userInfo in url: {0} ... url: {1}", userInfo, url); + _logger.LogInformation("Found userInfo in url: {0} ... url: {1}", userInfo, url); url = url.Replace(userInfo + "@", string.Empty); } @@ -421,11 +421,11 @@ namespace Emby.Server.Implementations.HttpClientManager { if (options.LogRequestAsDebug) { - _logger.Debug("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); + _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); } else { - _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); + _logger.LogInformation("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); } } @@ -595,11 +595,11 @@ namespace Emby.Server.Implementations.HttpClientManager { if (options.LogRequestAsDebug) { - _logger.Debug("HttpClientManager.GetTempFileResponse url: {0}", options.Url); + _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url); } else { - _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url); + _logger.LogInformation("HttpClientManager.GetTempFileResponse url: {0}", options.Url); } } @@ -685,7 +685,7 @@ namespace Emby.Server.Implementations.HttpClientManager { if (options.LogErrors) { - _logger.ErrorException("Error " + webException.Status + " getting response from " + options.Url, webException); + _logger.LogError(webException, "Error {status} getting response from {url}", webException.Status, options.Url); } var exception = new HttpException(webException.Message, webException); @@ -723,7 +723,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (options.LogErrors) { - _logger.ErrorException("Error getting response from " + options.Url, ex); + _logger.LogError(ex, "Error getting response from {url}", options.Url); } return ex; @@ -789,7 +789,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (options.LogErrors) { - _logger.Error(msg); + _logger.LogError(msg); } client.LastTimeout = DateTime.UtcNow; @@ -824,7 +824,7 @@ namespace Emby.Server.Implementations.HttpClientManager { var msg = reader.ReadToEnd(); - _logger.Error(msg); + _logger.LogError(msg); } } } diff --git a/Emby.Server.Implementations/HttpServer/FileWriter.cs b/Emby.Server.Implementations/HttpServer/FileWriter.cs index 353ba5282..1a875e533 100644 --- a/Emby.Server.Implementations/HttpServer/FileWriter.cs +++ b/Emby.Server.Implementations/HttpServer/FileWriter.cs @@ -5,7 +5,7 @@ using System.Net; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using System.Linq; @@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.HttpServer var rangeString = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength); Headers["Content-Range"] = rangeString; - Logger.Info("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString); + Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString); } /// @@ -173,7 +173,7 @@ namespace Emby.Server.Implementations.HttpServer if (extension == null || !SkipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { - Logger.Debug("Transmit file {0}", path); + Logger.LogDebug("Transmit file {0}", path); } //var count = FileShare == FileShareMode.ReadWrite ? TotalContentLength : 0; diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 0093258e3..704b7f8a6 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -252,11 +252,11 @@ namespace Emby.Server.Implementations.HttpServer if (logExceptionStackTrace) { - _logger.ErrorException("Error processing request", ex); + _logger.LogError(ex, "Error processing request"); } else if (logExceptionMessage) { - _logger.Error(ex.Message); + _logger.LogError(ex.Message); } var httpRes = httpReq.Response; @@ -272,9 +272,9 @@ namespace Emby.Server.Implementations.HttpServer httpRes.ContentType = "text/html"; await Write(httpRes, NormalizeExceptionMessage(ex.Message)).ConfigureAwait(false); } - catch + catch (Exception errorEx) { - //_logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx); + _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)"); } } @@ -320,10 +320,10 @@ namespace Emby.Server.Implementations.HttpServer if (_listener != null) { - _logger.Info("Stopping HttpListener..."); + _logger.LogInformation("Stopping HttpListener..."); var task = _listener.Stop(); Task.WaitAll(task); - _logger.Info("HttpListener stopped"); + _logger.LogInformation("HttpListener stopped"); } } @@ -713,12 +713,12 @@ namespace Emby.Server.Implementations.HttpServer var pathParts = pathInfo.TrimStart('/').Split('/'); if (pathParts.Length == 0) { - _logger.Error("Path parts empty for PathInfo: {0}, Url: {1}", pathInfo, httpReq.RawUrl); + _logger.LogError("Path parts empty for PathInfo: {pathInfo}, Url: {RawUrl}", pathInfo, httpReq.RawUrl); return null; } string contentType; - var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, _logger, out contentType); + var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, out contentType); if (restPath != null) { @@ -729,7 +729,7 @@ namespace Emby.Server.Implementations.HttpServer }; } - _logger.Error("Could not find handler for {0}", pathInfo); + _logger.LogError("Could not find handler for {pathInfo}", pathInfo); return null; } @@ -783,7 +783,7 @@ namespace Emby.Server.Implementations.HttpServer ServiceController = new ServiceController(); - _logger.Info("Calling ServiceStack AppHost.Init"); + _logger.LogInformation("Calling ServiceStack AppHost.Init"); var types = services.Select(r => r.GetType()).ToArray(); @@ -825,7 +825,7 @@ namespace Emby.Server.Implementations.HttpServer }); } - return routes.ToArray(routes.Count); + return routes.ToArray(); } public Func GetParseFn(Type propertyType) @@ -853,7 +853,7 @@ namespace Emby.Server.Implementations.HttpServer //using (var reader = new StreamReader(stream)) //{ // var json = reader.ReadToEnd(); - // Logger.Info(json); + // logger.LogInformation(json); // return _jsonSerializer.DeserializeFromString(json, type); //} return _jsonSerializer.DeserializeFromStreamAsync(stream, type); @@ -919,7 +919,7 @@ namespace Emby.Server.Implementations.HttpServer return Task.CompletedTask; } - //_logger.Debug("Websocket message received: {0}", result.MessageType); + _logger.LogDebug("Websocket message received: {0}", result.MessageType); var tasks = _webSocketListeners.Select(i => Task.Run(async () => { @@ -929,7 +929,7 @@ namespace Emby.Server.Implementations.HttpServer } catch (Exception ex) { - _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType ?? string.Empty); + _logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty); } })); @@ -954,4 +954,4 @@ namespace Emby.Server.Implementations.HttpServer _listener.Start(UrlPrefixes); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index df493b4c3..73b2afe64 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -1,6 +1,6 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -37,12 +37,12 @@ namespace Emby.Server.Implementations.HttpServer /// /// Initializes a new instance of the class. /// - public HttpResultFactory(ILogManager logManager, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor) + public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor) { _fileSystem = fileSystem; _jsonSerializer = jsonSerializer; _brotliCompressor = brotliCompressor; - _logger = logManager.GetLogger("HttpResultFactory"); + _logger = loggerfactory.CreateLogger("HttpResultFactory"); } /// @@ -112,12 +112,15 @@ namespace Emby.Server.Implementations.HttpServer /// private IHasHeaders GetHttpResult(IRequest requestContext, byte[] content, string contentType, bool addCachePrevention, IDictionary responseHeaders = null) { + string compressionType = null; + bool isHeadRequest = false; + + if (requestContext != null) { + compressionType = GetCompressionType(requestContext, content, contentType); + isHeadRequest = string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase); + } + IHasHeaders result; - - var compressionType = requestContext == null ? null : GetCompressionType(requestContext, content, contentType); - - var isHeadRequest = string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase); - if (string.IsNullOrEmpty(compressionType)) { var contentLength = content.Length; @@ -791,4 +794,4 @@ namespace Emby.Server.Implementations.HttpServer { byte[] Compress(byte[] content); } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs b/Emby.Server.Implementations/HttpServer/LoggerUtils.cs index 3aa48efd4..5b7bbe79c 100644 --- a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs +++ b/Emby.Server.Implementations/HttpServer/LoggerUtils.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Globalization; using MediaBrowser.Model.Services; @@ -11,7 +11,7 @@ namespace Emby.Server.Implementations.HttpServer { if (headers == null) { - logger.Info("{0} {1}. UserAgent: {2}", "HTTP " + method, url, userAgent ?? string.Empty); + logger.LogInformation("{0} {1}. UserAgent: {2}", "HTTP " + method, url, userAgent ?? string.Empty); } else { @@ -30,7 +30,7 @@ namespace Emby.Server.Implementations.HttpServer index++; } - logger.Info("HTTP {0} {1}. {2}", method, url, headerText); + logger.LogInformation("HTTP {0} {1}. {2}", method, url, headerText); } } @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.HttpServer //var headerText = headers == null ? string.Empty : "Headers: " + string.Join(", ", headers.Where(i => i.Name.IndexOf("Access-", StringComparison.OrdinalIgnoreCase) == -1).Select(i => i.Name + "=" + i.Value).ToArray()); var headerText = string.Empty; - logger.Info("HTTP Response {0} to {1}. Time: {2}{3}. {4} {5}", statusCode, endPoint, Convert.ToInt32(durationMs).ToString(CultureInfo.InvariantCulture), logSuffix, url, headerText); + logger.LogInformation("HTTP Response {0} to {1}. Time: {2}{3}. {4} {5}", statusCode, endPoint, Convert.ToInt32(durationMs).ToString(CultureInfo.InvariantCulture), logSuffix, url, headerText); } } } diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs index 4177c7e78..dc20ee1a2 100644 --- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs +++ b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -226,4 +226,4 @@ namespace Emby.Server.Implementations.HttpServer public string StatusDescription { get; set; } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs index 385d19b6b..f38aa5ea0 100644 --- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs +++ b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Globalization; using System.Text; @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.HttpServer if (exception != null) { - _logger.ErrorException("Error processing request for {0}", exception, req.RawUrl); + _logger.LogError(exception, "Error processing request for {RawUrl}", req.RawUrl); if (!string.IsNullOrEmpty(exception.Message)) { diff --git a/Emby.Server.Implementations/HttpServer/StreamWriter.cs b/Emby.Server.Implementations/HttpServer/StreamWriter.cs index 3f394d3ac..0a44a5fe5 100644 --- a/Emby.Server.Implementations/HttpServer/StreamWriter.cs +++ b/Emby.Server.Implementations/HttpServer/StreamWriter.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs index d449e4424..8b5dfd444 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs @@ -1,7 +1,7 @@ using System.Text; using MediaBrowser.Common.Events; using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; @@ -180,7 +180,7 @@ namespace Emby.Server.Implementations.HttpServer if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase)) { // This info is useful sometimes but also clogs up the log - //_logger.Error("Received web socket message that is not a json structure: " + message); + _logger.LogDebug("Received web socket message that is not a json structure: {message}", message); return; } @@ -204,7 +204,7 @@ namespace Emby.Server.Implementations.HttpServer } catch (Exception ex) { - _logger.ErrorException("Error processing web socket message", ex); + _logger.LogError(ex, "Error processing web socket message"); } } diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs index 4be30f8b7..df484d04c 100644 --- a/Emby.Server.Implementations/IO/FileRefresher.cs +++ b/Emby.Server.Implementations/IO/FileRefresher.cs @@ -12,7 +12,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Threading; @@ -38,7 +38,7 @@ namespace Emby.Server.Implementations.IO public FileRefresher(string path, IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ITaskManager taskManager, ILogger logger, ITimerFactory timerFactory, IEnvironmentInfo environmentInfo, ILibraryManager libraryManager1) { - logger.Debug("New file refresher created for {0}", path); + logger.LogDebug("New file refresher created for {0}", path); Path = path; _fileSystem = fileSystem; @@ -108,7 +108,7 @@ namespace Emby.Server.Implementations.IO { lock (_timerLock) { - Logger.Debug("Resetting file refresher from {0} to {1}", Path, path); + Logger.LogDebug("Resetting file refresher from {0} to {1}", Path, path); Path = path; AddAffectedPath(path); @@ -130,7 +130,7 @@ namespace Emby.Server.Implementations.IO paths = _affectedPaths.ToList(); } - Logger.Debug("Timer stopped."); + Logger.LogDebug("Timer stopped."); DisposeTimer(); EventHelper.FireEventIfNotNull(Completed, this, EventArgs.Empty, Logger); @@ -141,7 +141,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error processing directory changes", ex); + Logger.LogError(ex, "Error processing directory changes"); } } @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.IO continue; } - Logger.Info(item.Name + " (" + item.Path + ") will be refreshed."); + Logger.LogInformation("{name} ({path}}) will be refreshed.", item.Name, item.Path); try { @@ -172,11 +172,11 @@ namespace Emby.Server.Implementations.IO // For now swallow and log. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable) // Should we remove it from it's parent? - Logger.ErrorException("Error refreshing {0}", ex, item.Name); + Logger.LogError(ex, "Error refreshing {name}", item.Name); } catch (Exception ex) { - Logger.ErrorException("Error refreshing {0}", ex, item.Name); + Logger.LogError(ex, "Error refreshing {name}", item.Name); } } } diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs index 00fe447f0..ca5810fd6 100644 --- a/Emby.Server.Implementations/IO/LibraryMonitor.cs +++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs @@ -9,7 +9,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Threading; @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error in ReportFileSystemChanged for {0}", ex, path); + Logger.LogError(ex, "Error in ReportFileSystemChanged for {path}", path); } } } @@ -141,7 +141,7 @@ namespace Emby.Server.Implementations.IO /// /// Initializes a new instance of the class. /// - public LibraryMonitor(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ITimerFactory timerFactory, ISystemEvents systemEvents, IEnvironmentInfo environmentInfo) + public LibraryMonitor(ILoggerFactory loggerFactory, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ITimerFactory timerFactory, ISystemEvents systemEvents, IEnvironmentInfo environmentInfo) { if (taskManager == null) { @@ -150,7 +150,7 @@ namespace Emby.Server.Implementations.IO LibraryManager = libraryManager; TaskManager = taskManager; - Logger = logManager.GetLogger(GetType().Name); + Logger = loggerFactory.CreateLogger(GetType().Name); ConfigurationManager = configurationManager; _fileSystem = fileSystem; _timerFactory = timerFactory; @@ -291,7 +291,7 @@ namespace Emby.Server.Implementations.IO if (!_fileSystem.DirectoryExists(path)) { // Seeing a crash in the mono runtime due to an exception being thrown on a different thread - Logger.Info("Skipping realtime monitor for {0} because the path does not exist", path); + Logger.LogInformation("Skipping realtime monitor for {0} because the path does not exist", path); return; } @@ -344,7 +344,7 @@ namespace Emby.Server.Implementations.IO if (_fileSystemWatchers.TryAdd(path, newWatcher)) { newWatcher.EnableRaisingEvents = true; - Logger.Info("Watching directory " + path); + Logger.LogInformation("Watching directory " + path); } else { @@ -354,7 +354,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error watching path: {0}", ex, path); + Logger.LogError(ex, "Error watching path: {path}", path); } }); } @@ -382,7 +382,7 @@ namespace Emby.Server.Implementations.IO { using (watcher) { - Logger.Info("Stopping directory watching for path {0}", watcher.Path); + Logger.LogInformation("Stopping directory watching for path {path}", watcher.Path); watcher.Created -= watcher_Changed; watcher.Deleted -= watcher_Changed; @@ -439,7 +439,7 @@ namespace Emby.Server.Implementations.IO var ex = e.GetException(); var dw = (FileSystemWatcher)sender; - Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex); + Logger.LogError(ex, "Error in Directory watcher for: {path}", dw.Path); DisposeWatcher(dw, true); } @@ -453,7 +453,7 @@ namespace Emby.Server.Implementations.IO { try { - //Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath); + //logger.LogDebug("Changed detected of type " + e.ChangeType + " to " + e.FullPath); var path = e.FullPath; @@ -461,7 +461,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath); + Logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath); } } @@ -487,13 +487,13 @@ namespace Emby.Server.Implementations.IO { if (_fileSystem.AreEqual(i, path)) { - //Logger.Debug("Ignoring change to {0}", path); + Logger.LogDebug("Ignoring change to {path}", path); return true; } if (_fileSystem.ContainsSubPath(i, path)) { - //Logger.Debug("Ignoring change to {0}", path); + Logger.LogDebug("Ignoring change to {path}", path); return true; } @@ -503,7 +503,7 @@ namespace Emby.Server.Implementations.IO { if (_fileSystem.AreEqual(parent, path)) { - //Logger.Debug("Ignoring change to {0}", path); + Logger.LogDebug("Ignoring change to {path}", path); return true; } } diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 66d7802c6..8819449b5 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -5,7 +5,7 @@ using System.IO; using System.Linq; using System.Text; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; namespace Emby.Server.Implementations.IO @@ -175,7 +175,7 @@ namespace Emby.Server.Implementations.IO path = System.IO.Path.GetFullPath(path); return path; } - catch (ArgumentException ex) + catch (ArgumentException) { return filePath; } @@ -395,7 +395,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error determining CreationTimeUtc for {0}", ex, info.FullName); + Logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName); return DateTime.MinValue; } } @@ -434,7 +434,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error determining LastAccessTimeUtc for {0}", ex, info.FullName); + Logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName); return DateTime.MinValue; } } diff --git a/Emby.Server.Implementations/IO/SharpCifs/Config.cs b/Emby.Server.Implementations/IO/SharpCifs/Config.cs index 3fd0e5bd6..324a9c494 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Config.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Config.cs @@ -89,7 +89,7 @@ namespace SharpCifs { Runtime.GetBytesForString(string.Empty, DefaultOemEncoding); } - catch (Exception ex) + catch (Exception) { if (_log.Level >= 2) { diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs index 786b0ac12..e82af2b0c 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs @@ -153,7 +153,7 @@ namespace SharpCifs.Dcerpc DcerpcMessage bind = new DcerpcBind(Binding, this); Sendrecv(bind); } - catch (IOException ioe) + catch (IOException) { State = 0; throw; diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs index 6c37d57a4..15ae494be 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs @@ -130,7 +130,7 @@ namespace SharpCifs.Netbios { name = Runtime.GetStringForBytes(tmp, 0, length).Trim(); } - catch (Exception ex) + catch (Exception) { } diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs index 01700e64a..0d7840a64 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs @@ -117,8 +117,9 @@ namespace SharpCifs.Netbios { Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255")); } - catch (Exception ex) + catch (Exception) { + } _sndBuf = new byte[SndBufSize]; @@ -302,7 +303,10 @@ namespace SharpCifs.Netbios } } - catch (TimeoutException) { } + catch (TimeoutException) + { + + } catch (Exception ex) { if (_log.Level > 2) diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs index 44266f974..aa52ee1db 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs @@ -192,7 +192,7 @@ namespace SharpCifs.Smb catch (Exception e) { throw new SmbException(e.Message, e); - } + } } default: diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs index 4432e62fb..8560a2dc2 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +// TODO: @bond Remove namespace SharpCifs.Util.Sharpen { internal static class Collections diff --git a/Emby.Server.Implementations/IO/StreamHelper.cs b/Emby.Server.Implementations/IO/StreamHelper.cs index 48a5063e8..e91817611 100644 --- a/Emby.Server.Implementations/IO/StreamHelper.cs +++ b/Emby.Server.Implementations/IO/StreamHelper.cs @@ -163,7 +163,7 @@ namespace Emby.Server.Implementations.IO var bytesRead = await CopyToAsyncInternal(source, target, buffer, cancellationToken).ConfigureAwait(false); //var position = fs.Position; - //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); + //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); if (bytesRead == 0) { diff --git a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs index 59f0a9fc9..7fb979d66 100644 --- a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs +++ b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs @@ -9,7 +9,7 @@ using System.Linq; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library { diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 17516d6b9..451f16bef 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -12,7 +12,7 @@ using MediaBrowser.Controller.Resolvers; using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using Emby.Naming.Audio; using Emby.Naming.Common; @@ -351,7 +351,7 @@ namespace Emby.Server.Implementations.Library if (item is LiveTvProgram) { - _logger.Debug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}", + _logger.LogDebug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}", item.GetType().Name, item.Name ?? "Unknown name", item.Path ?? string.Empty, @@ -359,7 +359,7 @@ namespace Emby.Server.Implementations.Library } else { - _logger.Info("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}", + _logger.LogInformation("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}", item.GetType().Name, item.Name ?? "Unknown name", item.Path ?? string.Empty, @@ -372,7 +372,7 @@ namespace Emby.Server.Implementations.Library foreach (var metadataPath in GetMetadataPaths(item, children)) { - _logger.Debug("Deleting path {0}", metadataPath); + _logger.LogDebug("Deleting path {0}", metadataPath); try { @@ -384,7 +384,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error deleting {0}", ex, metadataPath); + _logger.LogError(ex, "Error deleting {metadataPath}", metadataPath); } } @@ -398,14 +398,13 @@ namespace Emby.Server.Implementations.Library { try { + _logger.LogDebug("Deleting path {path}", fileSystemInfo.FullName); if (fileSystemInfo.IsDirectory) { - _logger.Debug("Deleting path {0}", fileSystemInfo.FullName); _fileSystem.DeleteDirectory(fileSystemInfo.FullName, true); } else { - _logger.Debug("Deleting path {0}", fileSystemInfo.FullName); _fileSystem.DeleteFile(fileSystemInfo.FullName); } } @@ -489,7 +488,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error in {0} resolving {1}", ex, resolver.GetType().Name, args.Path); + _logger.LogError(ex, "Error in {resolver} resolving {path}", resolver.GetType().Name, args.Path); return null; } } @@ -587,7 +586,7 @@ namespace Emby.Server.Implementations.Library { if (parent != null && parent.IsPhysicalRoot) { - _logger.ErrorException("Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", ex, isPhysicalRoot, isVf); + _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPhysicalRoot, isVf); files = new FileSystemMetadata[] { }; } @@ -639,7 +638,7 @@ namespace Emby.Server.Implementations.Library foreach (var dupe in dupes) { - _logger.Info("Found duplicate path: {0}", dupe); + _logger.LogInformation("Found duplicate path: {0}", dupe); } var newList = list.Except(dupes, StringComparer.OrdinalIgnoreCase).Select(_fileSystem.GetDirectoryInfo).ToList(); @@ -713,7 +712,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error resolving path {0}", ex, f.FullName); + _logger.LogError(ex, "Error resolving path {path}", f.FullName); return null; } }).Where(i => i != null); @@ -730,12 +729,12 @@ namespace Emby.Server.Implementations.Library _fileSystem.CreateDirectory(rootFolderPath); - var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)); + var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath))).DeepCopy(); // In case program data folder was moved if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal)) { - _logger.Info("Resetting root folder path to {0}", rootFolderPath); + _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath); rootFolder.Path = rootFolderPath; } @@ -799,13 +798,13 @@ namespace Emby.Server.Implementations.Library if (tmpItem == null) { - tmpItem = (UserRootFolder)ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath)); + tmpItem = ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath))).DeepCopy(); } // In case program data folder was moved if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal)) { - _logger.Info("Resetting user root folder path to {0}", userRootPath); + _logger.LogInformation("Resetting user root folder path to {0}", userRootPath); tmpItem.Path = userRootPath; } @@ -827,7 +826,7 @@ namespace Emby.Server.Implementations.Library throw new ArgumentNullException("path"); } - //_logger.Info("FindByPath {0}", path); + //_logger.LogInformation("FindByPath {0}", path); var query = new InternalItemsQuery { @@ -1065,11 +1064,11 @@ namespace Emby.Server.Implementations.Library await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false); // Start by just validating the children of the root, but go no further - await RootFolder.ValidateChildren(new SimpleProgress(), cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: false); + await RootFolder.ValidateChildren(new SimpleProgress(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false); await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false); - await GetUserRootFolder().ValidateChildren(new SimpleProgress(), cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: false).ConfigureAwait(false); + await GetUserRootFolder().ValidateChildren(new SimpleProgress(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false).ConfigureAwait(false); // Quickly scan CollectionFolders for changes foreach (var folder in GetUserRootFolder().Children.OfType().ToList()) @@ -1080,7 +1079,7 @@ namespace Emby.Server.Implementations.Library private async Task PerformLibraryValidation(IProgress progress, CancellationToken cancellationToken) { - _logger.Info("Validating media library"); + _logger.LogInformation("Validating media library"); await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false); @@ -1089,7 +1088,7 @@ namespace Emby.Server.Implementations.Library innerProgress.RegisterAction(pct => progress.Report(pct * .96)); // Now validate the entire media library - await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: true).ConfigureAwait(false); + await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: true).ConfigureAwait(false); progress.Report(96); @@ -1135,7 +1134,7 @@ namespace Emby.Server.Implementations.Library progress.Report(innerPercent); }); - _logger.Debug("Running post-scan task {0}", task.GetType().Name); + _logger.LogDebug("Running post-scan task {0}", task.GetType().Name); try { @@ -1143,12 +1142,12 @@ namespace Emby.Server.Implementations.Library } catch (OperationCanceledException) { - _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name); + _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name); throw; } catch (Exception ex) { - _logger.ErrorException("Error running postscan task", ex); + _logger.LogError(ex, "Error running postscan task"); } numComplete++; @@ -1199,7 +1198,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error resolving shortcut file {0}", ex, i); + _logger.LogError(ex, "Error resolving shortcut file {file}", i); return null; } }) @@ -1262,7 +1261,7 @@ namespace Emby.Server.Implementations.Library item = RetrieveItem(id); - //_logger.Debug("GetitemById {0}", id); + //_logger.LogDebug("GetitemById {0}", id); if (item != null) { @@ -1440,7 +1439,7 @@ namespace Emby.Server.Implementations.Library return true; } - //_logger.Debug("Query requires ancestor query due to type: " + i.GetType().Name); + //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name); return false; })) @@ -1493,7 +1492,7 @@ namespace Emby.Server.Implementations.Library return new QueryResult { - Items = list.ToArray(list.Count) + Items = list.ToArray() }; } @@ -1506,7 +1505,7 @@ namespace Emby.Server.Implementations.Library return true; } - //_logger.Debug("Query requires ancestor query due to type: " + i.GetType().Name); + //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name); return false; })) @@ -1650,7 +1649,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting intros", ex); + _logger.LogError(ex, "Error getting intros"); return new List(); } @@ -1670,7 +1669,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting intro files", ex); + _logger.LogError(ex, "Error getting intro files"); return new List(); } @@ -1693,7 +1692,7 @@ namespace Emby.Server.Implementations.Library if (video == null) { - _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value); + _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value); } } else if (!string.IsNullOrEmpty(info.Path)) @@ -1705,7 +1704,7 @@ namespace Emby.Server.Implementations.Library if (video == null) { - _logger.Error("Intro resolver returned null for {0}.", info.Path); + _logger.LogError("Intro resolver returned null for {path}.", info.Path); } else { @@ -1724,12 +1723,12 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error resolving path {0}.", ex, info.Path); + _logger.LogError(ex, "Error resolving path {path}.", info.Path); } } else { - _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId."); + _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId."); } return video; @@ -1873,7 +1872,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error in ItemAdded event handler", ex); + _logger.LogError(ex, "Error in ItemAdded event handler"); } } } @@ -1904,7 +1903,7 @@ namespace Emby.Server.Implementations.Library } //var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name; - //_logger.Debug("Saving {0} to database.", logName); + //_logger.LogDebug("Saving {0} to database.", logName); ItemRepository.SaveItems(items, cancellationToken); @@ -1929,7 +1928,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error in ItemUpdated event handler", ex); + _logger.LogError(ex, "Error in ItemUpdated event handler"); } } } @@ -1965,7 +1964,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error in ItemRemoved event handler", ex); + _logger.LogError(ex, "Error in ItemRemoved event handler"); } } } @@ -2176,7 +2175,7 @@ namespace Emby.Server.Implementations.Library if (refresh) { item.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None); - _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.Normal); + _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal); } return item; @@ -2231,7 +2230,7 @@ namespace Emby.Server.Implementations.Library if (refresh) { - _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { // Need to force save to increment DateLastSaved ForceSave = true @@ -2295,7 +2294,7 @@ namespace Emby.Server.Implementations.Library if (refresh) { - _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { // Need to force save to increment DateLastSaved ForceSave = true @@ -2369,7 +2368,7 @@ namespace Emby.Server.Implementations.Library if (refresh) { - _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { // Need to force save to increment DateLastSaved ForceSave = true @@ -2808,7 +2807,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting person", ex); + _logger.LogError(ex, "Error getting person"); return null; } @@ -2836,7 +2835,7 @@ namespace Emby.Server.Implementations.Library { try { - _logger.Debug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url); + _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url); await _providerManagerFactory().SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index e027e133f..d0b3152ba 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System.Collections.Generic; using MediaBrowser.Model.Serialization; @@ -48,7 +48,7 @@ namespace Emby.Server.Implementations.Library { mediaInfo = _json.DeserializeFromFile(cacheFilePath); - //_logger.Debug("Found cached media info"); + //_logger.LogDebug("Found cached media info"); } catch { @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Library delayMs = Math.Max(3000, delayMs); if (delayMs > 0) { - _logger.Info("Waiting {0}ms before probing the live stream", delayMs); + _logger.LogInformation("Waiting {0}ms before probing the live stream", delayMs); await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); } } @@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.Library Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); _json.SerializeToFile(mediaInfo, cacheFilePath); - //_logger.Debug("Saved media info to {0}", cacheFilePath); + //_logger.LogDebug("Saved media info to {0}", cacheFilePath); } } @@ -104,7 +104,7 @@ namespace Emby.Server.Implementations.Library mediaStreams = newList; } - _logger.Info("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); mediaSource.Bitrate = mediaInfo.Bitrate; mediaSource.Container = mediaInfo.Container; diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 0dc436800..e5fd28997 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -4,9 +4,10 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Persistence; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -127,7 +128,7 @@ namespace Emby.Server.Implementations.Library if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder && !mediaSources[0].MediaStreams.Any(i => i.Type == MediaStreamType.Audio || i.Type == MediaStreamType.Video)) { - await item.RefreshMetadata(new MediaBrowser.Controller.Providers.MetadataRefreshOptions(_fileSystem) + await item.RefreshMetadata(new MediaBrowser.Controller.Providers.MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { EnableRemoteContentProbe = true, MetadataRefreshMode = MediaBrowser.Controller.Providers.MetadataRefreshMode.FullRefresh @@ -255,7 +256,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting media sources", ex); + _logger.LogError(ex, "Error getting media sources"); return new List(); } } @@ -476,12 +477,12 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error probing live tv stream", ex); + _logger.LogError(ex, "Error probing live tv stream"); AddMediaInfo(mediaSource, isAudio); } var json = _jsonSerializer.SerializeToString(mediaSource); - _logger.Info("Live stream opened: " + json); + _logger.LogInformation("Live stream opened: " + json); var clone = _jsonSerializer.DeserializeFromString(json); if (!request.UserId.Equals(Guid.Empty)) @@ -624,7 +625,7 @@ namespace Emby.Server.Implementations.Library { mediaInfo = _jsonSerializer.DeserializeFromFile(cacheFilePath); - //_logger.Debug("Found cached media info"); + //_logger.LogDebug("Found cached media info"); } catch (Exception ex) { @@ -658,7 +659,7 @@ namespace Emby.Server.Implementations.Library _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFilePath)); _jsonSerializer.SerializeToFile(mediaInfo, cacheFilePath); - //_logger.Debug("Saved media info to {0}", cacheFilePath); + //_logger.LogDebug("Saved media info to {0}", cacheFilePath); } } @@ -679,7 +680,7 @@ namespace Emby.Server.Implementations.Library mediaStreams = newList; } - _logger.Info("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); mediaSource.Bitrate = mediaInfo.Bitrate; mediaSource.Container = mediaInfo.Container; @@ -815,16 +816,16 @@ namespace Emby.Server.Implementations.Library { liveStream.ConsumerCount--; - _logger.Info("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liveStream.ConsumerCount); + _logger.LogInformation("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liveStream.ConsumerCount); if (liveStream.ConsumerCount <= 0) { _openStreams.Remove(id); - _logger.Info("Closing live stream {0}", id); + _logger.LogInformation("Closing live stream {0}", id); await liveStream.Close().ConfigureAwait(false); - _logger.Info("Live stream {0} closed successfully", id); + _logger.LogInformation("Live stream {0} closed successfully", id); } } } @@ -883,4 +884,4 @@ namespace Emby.Server.Implementations.Library } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index a33f101ae..dbfcf41e8 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using Emby.Naming.Audio; using System; using System.Collections.Generic; @@ -128,7 +128,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio { if (IsMultiDiscFolder(path, libraryOptions)) { - logger.Debug("Found multi-disc folder: " + path); + logger.LogDebug("Found multi-disc folder: " + path); discSubfolderCount++; } else diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs index 2ad839673..71ccd7da8 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Linq; diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index 556748183..143af4076 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -7,7 +7,7 @@ using System.IO; using System.Linq; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers { diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 1394e3858..68b6c57ae 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -14,7 +14,7 @@ using System.Linq; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers.Movies { diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs index d8343f7c6..0fe42fa73 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Model.Globalization; using Emby.Naming.Common; using Emby.Naming.TV; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers.TV { @@ -72,7 +72,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { if (episodeInfo.EpisodeNumber.HasValue && episodeInfo.SeasonNumber.HasValue) { - _logger.Debug("Found folder underneath series with episode number: {0}. Season {1}. Episode {2}", + _logger.LogDebug("Found folder underneath series with episode number: {0}. Season {1}. Episode {2}", path, episodeInfo.SeasonNumber.Value, episodeInfo.EpisodeNumber.Value); diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 951f439c2..32e8b6120 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using Emby.Naming.Common; using Emby.Naming.TV; using System; @@ -131,14 +131,14 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { //if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) //{ - // //logger.Debug("Igoring series file or folder marked hidden: {0}", child.FullName); + // //logger.LogDebug("Igoring series file or folder marked hidden: {0}", child.FullName); // continue; //} // Can't enforce this because files saved by Bitcasa are always marked System //if ((attributes & FileAttributes.System) == FileAttributes.System) //{ - // logger.Debug("Igoring series subfolder marked system: {0}", child.FullName); + // logger.LogDebug("Igoring series subfolder marked system: {0}", child.FullName); // continue; //} @@ -146,7 +146,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { if (IsSeasonFolder(child.FullName, isTvContentType, libraryManager)) { - //logger.Debug("{0} is a series because of season folder {1}.", path, child.FullName); + //logger.LogDebug("{0} is a series because of season folder {1}.", path, child.FullName); return true; } } @@ -181,7 +181,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV } } - //logger.Debug("{0} is not a series folder.", path); + //logger.LogDebug("{0} is not a series folder.", path); return false; } diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index 7f04ac5bc..1212ba549 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Search; using System; @@ -23,12 +23,12 @@ namespace Emby.Server.Implementations.Library private readonly IUserManager _userManager; private readonly ILogger _logger; - public SearchEngine(ILogManager logManager, ILibraryManager libraryManager, IUserManager userManager) + public SearchEngine(ILoggerFactory loggerFactory, ILibraryManager libraryManager, IUserManager userManager) { _libraryManager = libraryManager; _userManager = userManager; - _logger = logManager.GetLogger("SearchEngine"); + _logger = loggerFactory.CreateLogger("SearchEngine"); } public QueryResult GetSearchHints(SearchQuery query) @@ -161,8 +161,8 @@ namespace Emby.Server.Implementations.Library var searchQuery = new InternalItemsQuery(user) { SearchTerm = searchTerm, - ExcludeItemTypes = excludeItemTypes.ToArray(excludeItemTypes.Count), - IncludeItemTypes = includeItemTypes.ToArray(includeItemTypes.Count), + ExcludeItemTypes = excludeItemTypes.ToArray(), + IncludeItemTypes = includeItemTypes.ToArray(), Limit = query.Limit, IncludeItemsByName = string.IsNullOrEmpty(query.ParentId), ParentId = string.IsNullOrEmpty(query.ParentId) ? Guid.Empty : new Guid(query.ParentId), diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index 3714a7544..62371799b 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -32,10 +32,10 @@ namespace Emby.Server.Implementations.Library private Func _userManager; - public UserDataManager(ILogManager logManager, IServerConfigurationManager config, Func userManager) + public UserDataManager(ILoggerFactory loggerFactory, IServerConfigurationManager config, Func userManager) { _config = config; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _userManager = userManager; } diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs index da80a4824..ae3577b7d 100644 --- a/Emby.Server.Implementations/Library/UserManager.cs +++ b/Emby.Server.Implementations/Library/UserManager.cs @@ -15,7 +15,7 @@ using MediaBrowser.Model.Connect; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Users; using System; @@ -340,7 +340,7 @@ namespace Emby.Server.Implementations.Library UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1); } - _logger.Info("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied"); + _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied"); return success ? user : null; } @@ -392,7 +392,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error authenticating with provider {0}", ex, provider.Name); + _logger.LogError(ex, "Error authenticating with provider {provider}", provider.Name); return false; } @@ -461,7 +461,7 @@ namespace Emby.Server.Implementations.Library if (newValue >= maxCount) { - //_logger.Debug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture)); + //_logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture)); //user.Policy.IsDisabled = true; //fireLockout = true; @@ -575,7 +575,7 @@ namespace Emby.Server.Implementations.Library catch (Exception ex) { // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions - _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name); + _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name); } } @@ -599,7 +599,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path); + _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path); return null; } } @@ -613,7 +613,7 @@ namespace Emby.Server.Implementations.Library { foreach (var user in Users) { - await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); } } @@ -775,7 +775,7 @@ namespace Emby.Server.Implementations.Library } catch (IOException ex) { - _logger.ErrorException("Error deleting file {0}", ex, configPath); + _logger.LogError(ex, "Error deleting file {path}", configPath); } DeleteUserPolicy(user); @@ -1045,7 +1045,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error reading policy file: {0}", ex, path); + _logger.LogError(ex, "Error reading policy file: {path}", path); return GetDefaultPolicy(user); } @@ -1109,7 +1109,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error deleting policy file", ex); + _logger.LogError(ex, "Error deleting policy file"); } } @@ -1144,7 +1144,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error reading policy file: {0}", ex, path); + _logger.LogError(ex, "Error reading policy file: {path}", path); return new UserConfiguration(); } diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs index 42f922710..aae5751de 100644 --- a/Emby.Server.Implementations/Library/UserViewManager.cs +++ b/Emby.Server.Implementations/Library/UserViewManager.cs @@ -354,7 +354,7 @@ namespace Emby.Server.Implementations.Library Limit = limit * 5, IsPlayed = isPlayed, DtoOptions = options, - MediaTypes = mediaTypes.ToArray(mediaTypes.Count) + MediaTypes = mediaTypes.ToArray() }; if (parents.Count == 0) diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs index 4d718dbee..eee66c8ac 100644 --- a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs index cd2aab4c8..1686dc23c 100644 --- a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -70,7 +70,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {ArtistName}", name); } numComplete++; @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.Library.Validators continue; } - _logger.Info("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); + _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); _libraryManager.DeleteItem(item, new DeleteOptions { diff --git a/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs index ee6c4461c..ea1f2e552 100644 --- a/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs index f7fbb9331..070777475 100644 --- a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {GenreName}", name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs index be46decfb..4f4133340 100644 --- a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs @@ -3,7 +3,7 @@ using System; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Persistence; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs index d71e77a9a..775cde299 100644 --- a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {GenreName}", name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs index cd4021548..edc6f3ad6 100644 --- a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs index 98d53c125..b5ed1c0e6 100644 --- a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {GenreName}", name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs index 1f4e1de92..50c7cfbc6 100644 --- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; @@ -54,7 +54,7 @@ namespace Emby.Server.Implementations.Library.Validators var numPeople = people.Count; - _logger.Debug("Will refresh {0} people", numPeople); + _logger.LogDebug("Will refresh {0} people", numPeople); foreach (var person in people) { @@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.Library.Validators { var item = _libraryManager.GetPerson(person); - var options = new MetadataRefreshOptions(_fileSystem) + var options = new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ImageRefreshMode = MetadataRefreshMode.ValidationOnly, MetadataRefreshMode = MetadataRefreshMode.ValidationOnly @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error validating IBN entry {0}", ex, person); + _logger.LogError(ex, "Error validating IBN entry {person}", person); } // Update progress @@ -98,7 +98,7 @@ namespace Emby.Server.Implementations.Library.Validators foreach (var item in deadEntities) { - _logger.Info("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); + _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); _libraryManager.DeleteItem(item, new DeleteOptions { @@ -108,7 +108,7 @@ namespace Emby.Server.Implementations.Library.Validators progress.Report(100); - _logger.Info("People validation complete"); + _logger.LogInformation("People validation complete"); } } } diff --git a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs index d23efb6d3..45747dda1 100644 --- a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs index f306309b3..1a5ebac54 100644 --- a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {StudioName}", name); } numComplete++; @@ -77,7 +77,7 @@ namespace Emby.Server.Implementations.Library.Validators foreach (var item in deadEntities) { - _logger.Info("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); + _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); _libraryManager.DeleteItem(item, new DeleteOptions { diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 0c7980ca0..327b0181a 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -8,7 +8,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV { @@ -50,7 +50,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { onStarted(); - _logger.Info("Copying recording stream to file {0}", targetFile); + _logger.LogInformation("Copying recording stream to file {0}", targetFile); // The media source is infinite so we need to handle stopping ourselves var durationToken = new CancellationTokenSource(duration); @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await directStreamProvider.CopyToAsync(output, cancellationToken).ConfigureAwait(false); } - _logger.Info("Recording completed to file {0}", targetFile); + _logger.LogInformation("Recording completed to file {0}", targetFile); } private async Task RecordFromMediaSource(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false)) { - _logger.Info("Opened recording stream from tuner provider"); + _logger.LogInformation("Opened recording stream from tuner provider"); _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(targetFile)); @@ -86,7 +86,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { onStarted(); - _logger.Info("Copying recording stream to file {0}", targetFile); + _logger.LogInformation("Copying recording stream to file {0}", targetFile); // The media source if infinite so we need to handle stopping ourselves var durationToken = new CancellationTokenSource(duration); @@ -96,7 +96,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - _logger.Info("Recording completed to file {0}", targetFile); + _logger.LogInformation("Recording completed to file {0}", targetFile); } } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 167f2a84b..ef96510bd 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -12,7 +12,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; @@ -170,7 +170,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error creating virtual folder", ex); + _logger.LogError(ex, "Error creating virtual folder"); } pathsAdded.AddRange(pathsToCreate); @@ -196,13 +196,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error creating recording folders", ex); + _logger.LogError(ex, "Error creating recording folders"); } } private async Task RemovePathFromLibrary(string path) { - _logger.Debug("Removing path from library: {0}", path); + _logger.LogDebug("Removing path from library: {0}", path); var requiresRefresh = false; var virtualFolders = _libraryManager.GetVirtualFolders() @@ -224,7 +224,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error removing virtual folder", ex); + _logger.LogError(ex, "Error removing virtual folder"); } } else @@ -236,14 +236,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error removing media path", ex); + _logger.LogError(ex, "Error removing media path"); } } } if (requiresRefresh) { - _libraryManager.ValidateMediaLibrary(new SimpleProgress(), CancellationToken.None); + await _libraryManager.ValidateMediaLibrary(new SimpleProgress(), CancellationToken.None); } } @@ -342,7 +342,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error getting channels", ex); + _logger.LogError(ex, "Error getting channels"); } } @@ -364,7 +364,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error adding metadata", ex); + _logger.LogError(ex, "Error adding metadata"); } } } @@ -406,7 +406,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV foreach (var channel in channels) { - _logger.Info("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id); + _logger.LogInformation("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id); } result = new EpgChannelData(channels); @@ -595,7 +595,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error getting channels", ex); + _logger.LogError(ex, "Error getting channels"); } } @@ -718,7 +718,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } if (programInfo == null) { - _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); + _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate); } @@ -984,11 +984,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId)) { - _logger.Debug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); + _logger.LogDebug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); continue; } - _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); + _logger.LogDebug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false); @@ -996,7 +996,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (epgChannel == null) { - _logger.Debug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); + _logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); programs = new List(); } else @@ -1042,7 +1042,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public async Task GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, List currentLiveStreams, CancellationToken cancellationToken) { - _logger.Info("Streaming Channel " + channelId); + _logger.LogInformation("Streaming Channel " + channelId); var result = string.IsNullOrEmpty(streamId) ? null : @@ -1052,7 +1052,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { result.ConsumerCount++; - _logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount); + _logger.LogInformation("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount); return result; } @@ -1067,7 +1067,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV result.OriginalStreamId = streamId; - _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId); + _logger.LogInformation("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId); return result; } @@ -1174,7 +1174,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var timer = e.Argument; - _logger.Info("Recording timer fired for {0}.", timer.Name); + _logger.LogInformation("Recording timer fired for {0}.", timer.Name); try { @@ -1182,7 +1182,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (recordingEndDate <= DateTime.UtcNow) { - _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id); + _logger.LogWarning("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id); OnTimerOutOfDate(timer); return; } @@ -1190,7 +1190,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var registration = await _liveTvManager.GetRegistrationInfo("dvr").ConfigureAwait(false); if (!registration.IsValid) { - _logger.Warn("Emby Premiere required to use Emby DVR."); + _logger.LogWarning("Emby Premiere required to use Emby DVR."); OnTimerOutOfDate(timer); return; } @@ -1208,7 +1208,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } else { - _logger.Info("Skipping RecordStream because it's already in progress."); + _logger.LogInformation("Skipping RecordStream because it's already in progress."); } } catch (OperationCanceledException) @@ -1217,7 +1217,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error recording stream", ex); + _logger.LogError(ex, "Error recording stream"); } } @@ -1342,7 +1342,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } if (programInfo == null) { - _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); + _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate); } @@ -1390,9 +1390,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var duration = recordingEndDate - DateTime.UtcNow; - _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); - _logger.Info("Writing file to path: " + recordPath); + _logger.LogInformation("Writing file to path: " + recordPath); Action onStarted = async () => { @@ -1414,16 +1414,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false); recordingStatus = RecordingStatus.Completed; - _logger.Info("Recording completed: {0}", recordPath); + _logger.LogInformation("Recording completed: {recordPath}", recordPath); } catch (OperationCanceledException) { - _logger.Info("Recording stopped: {0}", recordPath); + _logger.LogInformation("Recording stopped: {recordPath}", recordPath); recordingStatus = RecordingStatus.Completed; } catch (Exception ex) { - _logger.ErrorException("Error recording to {0}", ex, recordPath); + _logger.LogError(ex, "Error recording to {recordPath}", recordPath); recordingStatus = RecordingStatus.Error; } @@ -1435,7 +1435,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error closing live stream", ex); + _logger.LogError(ex, "Error closing live stream"); } } @@ -1450,7 +1450,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10) { const int retryIntervalSeconds = 60; - _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds); + _logger.LogInformation("Retrying recording in {0} seconds.", retryIntervalSeconds); timer.Status = RecordingStatus.New; timer.PrePaddingSeconds = 0; @@ -1511,22 +1511,22 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error deleting 0-byte failed recording file {0}", ex, path); + _logger.LogError(ex, "Error deleting 0-byte failed recording file {path}", path); } } } private void TriggerRefresh(string path) { - _logger.Info("Triggering refresh on {0}", path); + _logger.LogInformation("Triggering refresh on {path}", path); var item = GetAffectedBaseItem(_fileSystem.GetDirectoryName(path)); if (item != null) { - _logger.Info("Refreshing recording parent {0}", item.Path); + _logger.LogInformation("Refreshing recording parent {path}", item.Path); - _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { RefreshPaths = new string[] { @@ -1642,7 +1642,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error deleting item", ex); + _logger.LogError(ex, "Error deleting item"); } } } @@ -1668,7 +1668,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error deleting recording", ex); + _logger.LogError(ex, "Error deleting recording"); } } } @@ -1773,14 +1773,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV UseShellExecute = false }); - _logger.Info("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); process.Exited += Process_Exited; process.Start(); } catch (Exception ex) { - _logger.ErrorException("Error running recording post processor", ex); + _logger.LogError(ex, "Error running recording post processor"); } } @@ -1794,7 +1794,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var process = (IProcess)sender; try { - _logger.Info("Recording post-processing script completed with exit code {0}", process.ExitCode); + _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode); } catch { @@ -1875,7 +1875,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } @@ -1890,7 +1890,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } @@ -1903,7 +1903,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } @@ -1916,7 +1916,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } } @@ -1984,7 +1984,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving nfo", ex); + _logger.LogError(ex, "Error saving nfo"); } } @@ -2790,7 +2790,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (!string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase)) { - _logger.Info("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url); + _logger.LogInformation("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url); configuredDevice.Url = device.Url; await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false); @@ -2807,14 +2807,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV foreach (var device in discoveredDevices) { - _logger.Info("Discovered tuner device {0} at {1}", host.Name, device.Url); + _logger.LogInformation("Discovered tuner device {0} at {1}", host.Name, device.Url); } return discoveredDevices; } catch (Exception ex) { - _logger.ErrorException("Error discovering tuner devices", ex); + _logger.LogError(ex, "Error discovering tuner devices"); return new List(); } @@ -2827,4 +2827,4 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return manager.GetConfiguration("xbmcmetadata"); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 9506a82be..4ea83b7ac 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -8,7 +8,6 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; - using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; @@ -18,7 +17,7 @@ using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Library; @@ -78,7 +77,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false); - _logger.Info("Recording completed to file {0}", targetFile); + _logger.LogInformation("Recording completed to file {0}", targetFile); } private EncodingOptions GetEncodingOptions() @@ -112,7 +111,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _process = process; var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; - _logger.Info(commandLineLogMessage); + _logger.LogInformation(commandLineLogMessage); var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt"); _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(logFilePath)); @@ -137,7 +136,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback StartStreamingLog(process.StandardError.BaseStream, _logFileStream); - _logger.Info("ffmpeg recording process started for {0}", _targetPath); + _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath); return _taskCompletionSource.Task; } @@ -270,14 +269,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { try { - _logger.Info("Stopping ffmpeg recording process for {0}", _targetPath); + _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath); //process.Kill(); _process.StandardInput.WriteLine("q"); } catch (Exception ex) { - _logger.ErrorException("Error stopping recording transcoding job for {0}", ex, _targetPath); + _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath); } if (_hasExited) @@ -287,7 +286,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.Info("Calling recording process.WaitForExit for {0}", _targetPath); + _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath); if (_process.WaitForExit(10000)) { @@ -296,7 +295,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error waiting for recording process to exit for {0}", ex, _targetPath); + _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath); } if (_hasExited) @@ -306,13 +305,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.Info("Killing ffmpeg recording process for {0}", _targetPath); + _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath); _process.Kill(); } catch (Exception ex) { - _logger.ErrorException("Error killing recording transcoding job for {0}", ex, _targetPath); + _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath); } } } @@ -330,7 +329,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var exitCode = process.ExitCode; - _logger.Info("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath); + _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {path}", exitCode, _targetPath); if (exitCode == 0) { @@ -338,13 +337,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } else { - _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed. Exit code {1}", _targetPath, exitCode))); + _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed. Exit code {ExitCode}", _targetPath, exitCode))); } } catch { - _logger.Error("FFMpeg recording exited with an error for {0}.", _targetPath); - _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath))); + _logger.LogError("FFMpeg recording exited with an error for {path}.", _targetPath); + _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed", _targetPath))); } } @@ -358,7 +357,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error disposing recording log stream", ex); + _logger.LogError(ex, "Error disposing recording log stream"); } _logFileStream = null; @@ -388,8 +387,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error reading ffmpeg recording log", ex); + _logger.LogError(ex, "Error reading ffmpeg recording log"); } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 4ba2269a6..9f179dc2c 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (_items == null) { - Logger.Info("Loading live tv data from {0}", _dataPath); + Logger.LogInformation("Loading live tv data from {0}", _dataPath); _items = GetItemsFromFile(_dataPath); } return _items.ToList(); @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - Logger.ErrorException("Error deserializing {0}", ex, jsonFile); + Logger.LogError(ex, "Error deserializing {jsonFile}", jsonFile); } return new List(); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs index 63cd26c7e..620ba7650 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using MediaBrowser.Model.IO; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs index b5f93b882..5618579f6 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Events; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; @@ -122,7 +122,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (startDate < now) { - EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs { Argument = item }, Logger); + EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs { Argument = item }, base.Logger); return; } @@ -143,7 +143,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error scheduling wake timer", ex); + _logger.LogError(ex, "Error scheduling wake timer"); } } @@ -153,12 +153,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (_timers.TryAdd(item.Id, timer)) { - _logger.Info("Creating recording timer for {0}, {1}. Timer will fire in {2} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Creating recording timer for {id}, {name}. Timer will fire in {minutes} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); } else { timer.Dispose(); - _logger.Warn("Timer already exists for item {0}", item.Id); + _logger.LogWarning("Timer already exists for item {id}", item.Id); } } @@ -178,7 +178,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var timer = GetAll().FirstOrDefault(i => string.Equals(i.Id, timerId, StringComparison.OrdinalIgnoreCase)); if (timer != null) { - EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs { Argument = timer }, Logger); + EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs { Argument = timer }, base.Logger); } } diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 9021666a3..8fb3af211 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -4,7 +4,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; @@ -80,7 +80,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings if (string.IsNullOrEmpty(token)) { - _logger.Warn("SchedulesDirect token is empty, returning empty program list"); + _logger.LogWarning("SchedulesDirect token is empty, returning empty program list"); return programsInfo; } @@ -88,7 +88,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings string stationID = channelId; - _logger.Info("Channel Station ID is: " + stationID); + _logger.LogInformation("Channel Station ID is: " + stationID); List requestList = new List() { @@ -100,7 +100,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings }; var requestString = _jsonSerializer.SerializeToString(requestList); - _logger.Debug("Request string for schedules is: " + requestString); + _logger.LogDebug("Request string for schedules is: " + requestString); var httpOptions = new HttpRequestOptions() { @@ -120,7 +120,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings StreamReader reader = new StreamReader(response.Content); string responseString = reader.ReadToEnd(); var dailySchedules = _jsonSerializer.DeserializeFromString>(responseString); - _logger.Debug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect"); + _logger.LogDebug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect"); httpOptions = new HttpRequestOptions() { @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings var schedules = dailySchedules.SelectMany(d => d.programs); foreach (ScheduleDirect.Program schedule in schedules) { - //_logger.Debug("Proccesing Schedule for statio ID " + stationID + + //_logger.LogDebug("Proccesing Schedule for statio ID " + stationID + // " which corresponds to channel " + channelNumber + " and program id " + // schedule.programID + " which says it has images? " + // programDict[schedule.programID].hasImageArtwork); @@ -453,7 +453,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings url = apiUrl + "/image/" + uri; } } - //_logger.Debug("URL for image is : " + url); + //_logger.LogDebug("URL for image is : " + url); return url; } @@ -527,7 +527,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } catch (Exception ex) { - _logger.ErrorException("Error getting image info from schedules direct", ex); + _logger.LogError(ex, "Error getting image info from schedules direct"); return new List(); } @@ -557,35 +557,33 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { using (var httpResponse = await Get(options, false, info).ConfigureAwait(false)) + using (Stream responce = httpResponse.Content) { - using (Stream responce = httpResponse.Content) - { - var root = await _jsonSerializer.DeserializeFromStreamAsync>(responce).ConfigureAwait(false); + var root = await _jsonSerializer.DeserializeFromStreamAsync>(responce).ConfigureAwait(false); - if (root != null) + if (root != null) + { + foreach (ScheduleDirect.Headends headend in root) { - foreach (ScheduleDirect.Headends headend in root) + foreach (ScheduleDirect.Lineup lineup in headend.lineups) { - foreach (ScheduleDirect.Lineup lineup in headend.lineups) + lineups.Add(new NameIdPair { - lineups.Add(new NameIdPair - { - Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name, - Id = lineup.uri.Substring(18) - }); - } + Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name, + Id = lineup.uri.Substring(18) + }); } } - else - { - _logger.Info("No lineups available"); - } + } + else + { + _logger.LogInformation("No lineups available"); } } } catch (Exception ex) { - _logger.Error("Error getting headends", ex); + _logger.LogError(ex, "Error getting headends"); } return lineups; @@ -750,7 +748,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings CancellationToken = cancellationToken, LogErrorResponseBody = true }; - //_logger.Info("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " + + //_logger.LogInformation("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " + // httpOptions.RequestContent); using (var responce = await Post(httpOptions, false, null).ConfigureAwait(false)) @@ -758,7 +756,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings var root = await _jsonSerializer.DeserializeFromStreamAsync(responce.Content).ConfigureAwait(false); if (root.message == "OK") { - _logger.Info("Authenticated with Schedules Direct token: " + root.token); + _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token); return root.token; } @@ -780,7 +778,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings throw new ArgumentException("Listings Id required"); } - _logger.Info("Adding new LineUp "); + _logger.LogInformation("Adding new LineUp "); var httpOptions = new HttpRequestOptions() { @@ -823,7 +821,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings throw new Exception("token required"); } - _logger.Info("Headends on account "); + _logger.LogInformation("Headends on account "); var options = new HttpRequestOptions() { @@ -927,8 +925,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings using (var response = httpResponse.Content) { var root = await _jsonSerializer.DeserializeFromStreamAsync(response).ConfigureAwait(false); - _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect"); - _logger.Info("Mapping Stations to Channel"); + _logger.LogInformation("Found " + root.map.Count + " channels on the lineup on ScheduleDirect"); + _logger.LogInformation("Mapping Stations to Channel"); var allStations = root.stations ?? new List(); @@ -1298,4 +1296,4 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs new file mode 100644 index 000000000..4d7c7fef4 --- /dev/null +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -0,0 +1,303 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Emby.XmlTv.Classes; +using Emby.XmlTv.Entities; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Net; +using MediaBrowser.Common.Progress; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.LiveTv; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Implementations.LiveTv.Listings +{ + public class XmlTvListingsProvider : IListingsProvider + { + private readonly IServerConfigurationManager _config; + private readonly IHttpClient _httpClient; + private readonly ILogger _logger; + private readonly IFileSystem _fileSystem; + private readonly IZipClient _zipClient; + + public XmlTvListingsProvider(IServerConfigurationManager config, IHttpClient httpClient, ILogger logger, IFileSystem fileSystem, IZipClient zipClient) + { + _config = config; + _httpClient = httpClient; + _logger = logger; + _fileSystem = fileSystem; + _zipClient = zipClient; + } + + public string Name + { + get { return "XmlTV"; } + } + + public string Type + { + get { return "xmltv"; } + } + + private string GetLanguage(ListingsProviderInfo info) + { + if (!string.IsNullOrWhiteSpace(info.PreferredLanguage)) + { + return info.PreferredLanguage; + } + + return _config.Configuration.PreferredMetadataLanguage; + } + + private async Task GetXml(string path, CancellationToken cancellationToken) + { + _logger.LogInformation("xmltv path: {path}", path); + + if (!path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return UnzipIfNeeded(path, path); + } + + string cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml"; + string cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename); + if (_fileSystem.FileExists(cacheFile)) + { + return UnzipIfNeeded(path, cacheFile); + } + + _logger.LogInformation("Downloading xmltv listings from {path}", path); + + string tempFile = await _httpClient.GetTempFile(new HttpRequestOptions + { + CancellationToken = cancellationToken, + Url = path, + Progress = new SimpleProgress(), + DecompressionMethod = CompressionMethod.Gzip, + + // It's going to come back gzipped regardless of this value + // So we need to make sure the decompression method is set to gzip + EnableHttpCompression = true, + + UserAgent = "Emby/3.0" + + }).ConfigureAwait(false); + + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFile)); + + _fileSystem.CopyFile(tempFile, cacheFile, true); + + return UnzipIfNeeded(path, cacheFile); + } + + private string UnzipIfNeeded(string originalUrl, string file) + { + string ext = Path.GetExtension(originalUrl.Split('?')[0]); + + if (string.Equals(ext, ".gz", StringComparison.OrdinalIgnoreCase)) + { + try + { + string tempFolder = ExtractGz(file); + return FindXmlFile(tempFolder); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error extracting from gz file {file}", file); + } + + try + { + string tempFolder = ExtractFirstFileFromGz(file); + return FindXmlFile(tempFolder); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error extracting from zip file {file}", file); + } + } + + return file; + } + + private string ExtractFirstFileFromGz(string file) + { + using (var stream = _fileSystem.OpenRead(file)) + { + string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); + _fileSystem.CreateDirectory(tempFolder); + + _zipClient.ExtractFirstFileFromGz(stream, tempFolder, "data.xml"); + + return tempFolder; + } + } + + private string ExtractGz(string file) + { + using (var stream = _fileSystem.OpenRead(file)) + { + string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); + _fileSystem.CreateDirectory(tempFolder); + + _zipClient.ExtractAllFromGz(stream, tempFolder, true); + + return tempFolder; + } + } + + private string FindXmlFile(string directory) + { + return _fileSystem.GetFiles(directory, true) + .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase)) + .Select(i => i.FullName) + .FirstOrDefault(); + } + + public async Task> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(channelId)) + { + throw new ArgumentNullException("channelId"); + } + + /* + if (!await EmbyTV.EmbyTVRegistration.Instance.EnableXmlTv().ConfigureAwait(false)) + { + var length = endDateUtc - startDateUtc; + if (length.TotalDays > 1) + { + endDateUtc = startDateUtc.AddDays(1); + } + }*/ + + _logger.LogDebug("Getting xmltv programs for channel {id}", channelId); + + string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + _logger.LogDebug("Opening XmlTvReader for {path}", path); + var reader = new XmlTvReader(path, GetLanguage(info)); + + return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken) + .Select(p => GetProgramInfo(p, info)); + } + + private ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info) + { + string episodeTitle = program.Episode?.Title; + + var programInfo = new ProgramInfo + { + ChannelId = program.ChannelId, + EndDate = program.EndDate.UtcDateTime, + EpisodeNumber = program.Episode?.Episode, + EpisodeTitle = episodeTitle, + Genres = program.Categories, + StartDate = program.StartDate.UtcDateTime, + Name = program.Title, + Overview = program.Description, + ProductionYear = program.CopyrightDate?.Year, + SeasonNumber = program.Episode?.Series, + IsSeries = program.Episode != null, + IsRepeat = program.IsPreviouslyShown && !program.IsNew, + IsPremiere = program.Premiere != null, + IsKids = program.Categories.Any(c => info.KidsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsMovie = program.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsNews = program.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsSports = program.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + ImageUrl = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source) ? program.Icon.Source : null, + HasImage = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source), + OfficialRating = program.Rating != null && !String.IsNullOrEmpty(program.Rating.Value) ? program.Rating.Value : null, + CommunityRating = program.StarRating, + SeriesId = program.Episode == null ? null : program.Title.GetMD5().ToString("N") + }; + + if (string.IsNullOrWhiteSpace(program.ProgramId)) + { + string uniqueString = (program.Title ?? string.Empty) + (episodeTitle ?? string.Empty) /*+ (p.IceTvEpisodeNumber ?? string.Empty)*/; + + if (programInfo.SeasonNumber.HasValue) + { + uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture); + } + if (programInfo.EpisodeNumber.HasValue) + { + uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture); + } + + programInfo.ShowId = uniqueString.GetMD5().ToString("N"); + + // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped + if (programInfo.IsSeries + && !programInfo.IsRepeat + && (programInfo.EpisodeNumber ?? 0) == 0) + { + programInfo.ShowId = programInfo.ShowId + programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture); + } + } + else + { + programInfo.ShowId = program.ProgramId; + } + + // Construct an id from the channel and start date + programInfo.Id = String.Format("{0}_{1:O}", program.ChannelId, program.StartDate); + + if (programInfo.IsMovie) + { + programInfo.IsSeries = false; + programInfo.EpisodeNumber = null; + programInfo.EpisodeTitle = null; + } + + return programInfo; + } + + public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings) + { + // Assume all urls are valid. check files for existence + if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !_fileSystem.FileExists(info.Path)) + { + throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path); + } + + return Task.CompletedTask; + } + + public async Task> GetLineups(ListingsProviderInfo info, string country, string location) + { + // In theory this should never be called because there is always only one lineup + string path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false); + _logger.LogDebug("Opening XmlTvReader for {path}", path); + var reader = new XmlTvReader(path, GetLanguage(info)); + IEnumerable results = reader.GetChannels(); + + // Should this method be async? + return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList(); + } + + public async Task> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken) + { + // In theory this should never be called because there is always only one lineup + string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + _logger.LogDebug("Opening XmlTvReader for {path}", path); + var reader = new XmlTvReader(path, GetLanguage(info)); + IEnumerable results = reader.GetChannels(); + + // Should this method be async? + return results.Select(c => new ChannelInfo + { + Id = c.Id, + Name = c.DisplayName, + ImageUrl = c.Icon != null && !String.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null, + Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number + + }).ToList(); + } + } +} diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs index 56b3b5e4b..6fe578715 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -139,7 +139,7 @@ namespace Emby.Server.Implementations.LiveTv dto.ProgramId = GetInternalProgramId(info.ProgramId).ToString("N"); } - dto.DayPattern = info.Days == null ? null : GetDayPattern(info.Days.ToArray(info.Days.Count)); + dto.DayPattern = info.Days == null ? null : GetDayPattern(info.Days.ToArray()); FillImages(dto, info.Name, info.SeriesId); @@ -170,6 +170,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } image = librarySeries.GetImageInfo(ImageType.Backdrop, 0); @@ -185,6 +186,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -212,6 +214,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } @@ -230,6 +233,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -260,6 +264,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } image = librarySeries.GetImageInfo(ImageType.Backdrop, 0); @@ -275,6 +280,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -333,6 +339,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -376,7 +383,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting image info for {0}", ex, info.Name); + _logger.LogError(ex, "Error getting image info for {name}", info.Name); } return null; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 9cdf105d7..ee2a9fe4b 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Common; -using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Progress; using MediaBrowser.Controller.Configuration; @@ -14,13 +13,11 @@ using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Serialization; using System; -using System.Collections.Concurrent; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -29,7 +26,6 @@ using MediaBrowser.Common.Events; using MediaBrowser.Common.Security; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.IO; using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; @@ -263,7 +259,7 @@ namespace Emby.Server.Implementations.LiveTv var channel = (LiveTvChannel)_libraryManager.GetItemById(id); isVideo = channel.ChannelType == ChannelType.TV; service = GetService(channel); - _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId); + _logger.LogInformation("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId); var supportsManagedStream = service as ISupportsDirectStreamProvider; if (supportsManagedStream != null) @@ -282,7 +278,7 @@ namespace Emby.Server.Implementations.LiveTv var startTime = DateTime.UtcNow; await liveStream.Open(cancellationToken).ConfigureAwait(false); var endTime = DateTime.UtcNow; - _logger.Info("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); + _logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); } info.RequiresClosing = true; @@ -1093,7 +1089,7 @@ namespace Emby.Server.Implementations.LiveTv { cancellationToken.ThrowIfCancellationRequested(); - _logger.Debug("Refreshing guide from {0}", service.Name); + _logger.LogDebug("Refreshing guide from {name}", service.Name); try { @@ -1112,7 +1108,7 @@ namespace Emby.Server.Implementations.LiveTv catch (Exception ex) { cleanDatabase = false; - _logger.ErrorException("Error refreshing channels for service", ex); + _logger.LogError(ex, "Error refreshing channels for service"); } numComplete++; @@ -1140,7 +1136,7 @@ namespace Emby.Server.Implementations.LiveTv var dtoOptions = new DtoOptions(); var fields = dtoOptions.Fields.ToList(); fields.Remove(ItemFields.BasicSyncInfo); - dtoOptions.Fields = fields.ToArray(fields.Count); + dtoOptions.Fields = fields.ToArray(); progress.Report(100); } @@ -1175,7 +1171,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name); + _logger.LogError(ex, "Error getting channel information for {name}", channelInfo.Item2.Name); } numComplete++; @@ -1193,7 +1189,7 @@ namespace Emby.Server.Implementations.LiveTv var guideDays = GetGuideDays(); - _logger.Info("Refreshing guide with {0} days of guide data", guideDays); + _logger.LogInformation("Refreshing guide with {0} days of guide data", guideDays); cancellationToken.ThrowIfCancellationRequested(); @@ -1269,7 +1265,7 @@ namespace Emby.Server.Implementations.LiveTv } } - _logger.Debug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count); + _logger.LogDebug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count); if (newPrograms.Count > 0) { @@ -1292,7 +1288,7 @@ namespace Emby.Server.Implementations.LiveTv } //currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken); - await currentChannel.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) + await currentChannel.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true @@ -1304,7 +1300,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name); + _logger.LogError(ex, "Error getting programs for channel {name}", currentChannel.Name); } numComplete++; @@ -1458,16 +1454,16 @@ namespace Emby.Server.Implementations.LiveTv { MediaTypes = new[] { MediaType.Video }, Recursive = true, - AncestorIds = folderIds.ToArray(folderIds.Count), + AncestorIds = folderIds.ToArray(), IsFolder = false, IsVirtualItem = false, Limit = limit, StartIndex = query.StartIndex, OrderBy = new[] { new ValueTuple(ItemSortBy.DateCreated, SortOrder.Descending) }, EnableTotalRecordCount = query.EnableTotalRecordCount, - IncludeItemTypes = includeItemTypes.ToArray(includeItemTypes.Count), - ExcludeItemTypes = excludeItemTypes.ToArray(excludeItemTypes.Count), - Genres = genres.ToArray(genres.Count), + IncludeItemTypes = includeItemTypes.ToArray(), + ExcludeItemTypes = excludeItemTypes.ToArray(), + Genres = genres.ToArray(), DtoOptions = dtoOptions }); @@ -1649,7 +1645,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List>(); } }); @@ -1725,7 +1721,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List>(); } }); @@ -1791,7 +1787,7 @@ namespace Emby.Server.Implementations.LiveTv var returnArray = returnList .OrderBy(i => i.StartDate) - .ToArray(returnList.Count); + .ToArray(); return new QueryResult { @@ -1880,7 +1876,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List>(); } }); @@ -1926,7 +1922,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List>(); } }); @@ -2162,7 +2158,7 @@ namespace Emby.Server.Implementations.LiveTv await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false); } - _logger.Info("New recording scheduled"); + _logger.LogInformation("New recording scheduled"); if (!(service is EmbyTV.EmbyTV)) { @@ -2183,7 +2179,7 @@ namespace Emby.Server.Implementations.LiveTv if (!registration.IsValid) { - _logger.Info("Creating series recordings requires an active Emby Premiere subscription."); + _logger.LogInformation("Creating series recordings requires an active Emby Premiere subscription."); return; } @@ -2338,7 +2334,7 @@ namespace Emby.Server.Implementations.LiveTv fields.Remove(ItemFields.CanDownload); fields.Remove(ItemFields.DisplayPreferencesId); fields.Remove(ItemFields.Etag); - options.Fields = fields.ToArray(fields.Count); + options.Fields = fields.ToArray(); } public Folder GetInternalLiveTvFolder(CancellationToken cancellationToken) @@ -2373,7 +2369,7 @@ namespace Emby.Server.Implementations.LiveTv { info.Id = Guid.NewGuid().ToString("N"); list.Add(info); - config.TunerHosts = list.ToArray(list.Count); + config.TunerHosts = list.ToArray(); } else { @@ -2392,27 +2388,31 @@ namespace Emby.Server.Implementations.LiveTv public async Task SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings) { + // Hack to make the object a pure ListingsProviderInfo instead of an AddListingProvider + // ServerConfiguration.SaveConfiguration crashes during xml serialization for AddListingProvider info = _jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info)); - var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); + IListingsProvider provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); if (provider == null) { - throw new ResourceNotFoundException(); + throw new ResourceNotFoundException( + string.Format("Couldn't find provider of type: '{0}'", info.Type) + ); } await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false); - var config = GetConfiguration(); + LiveTvOptions config = GetConfiguration(); - var list = config.ListingProviders.ToList(); - var index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase)); + List list = config.ListingProviders.ToList(); + int index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase)); if (index == -1 || string.IsNullOrWhiteSpace(info.Id)) { info.Id = Guid.NewGuid().ToString("N"); list.Add(info); - config.ListingProviders = list.ToArray(list.Count); + config.ListingProviders = list.ToArray(); } else { @@ -2451,7 +2451,7 @@ namespace Emby.Server.Implementations.LiveTv Name = tunerChannelId, Value = providerChannelId }); - listingsProviderInfo.ChannelMappings = list.ToArray(list.Count); + listingsProviderInfo.ChannelMappings = list.ToArray(); } _config.SaveConfiguration("livetv", config); @@ -2602,4 +2602,4 @@ namespace Emby.Server.Implementations.LiveTv return folders.Cast().ToList(); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs index 808672d46..d13f08b1b 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -29,14 +29,14 @@ namespace Emby.Server.Implementations.LiveTv private readonly IServerApplicationHost _appHost; private IApplicationPaths _appPaths; - public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost) + public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost) { _liveTvManager = liveTvManager; _jsonSerializer = jsonSerializer; _mediaSourceManager = mediaSourceManager; _mediaEncoder = mediaEncoder; _appHost = appHost; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _appPaths = appPaths; } @@ -106,7 +106,7 @@ namespace Emby.Server.Implementations.LiveTv openKeys.Add(item.GetType().Name); openKeys.Add(item.Id.ToString("N")); openKeys.Add(source.Id ?? string.Empty); - source.OpenToken = string.Join(StreamIdDelimeterString, openKeys.ToArray(openKeys.Count)); + source.OpenToken = string.Join(StreamIdDelimeterString, openKeys.ToArray()); } // Dummy this up so that direct play checks can still run @@ -116,7 +116,7 @@ namespace Emby.Server.Implementations.LiveTv } } - _logger.Debug("MediaSources: {0}", _jsonSerializer.SerializeToString(list)); + _logger.LogDebug("MediaSources: {0}", _jsonSerializer.SerializeToString(list)); return list; } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs index ca5e51971..ef2010ba6 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts var result = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false); var list = result.ToList(); - //Logger.Info("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list)); + //logger.LogInformation("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list)); if (!string.IsNullOrEmpty(key) && list.Count > 0) { @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error getting channel list", ex); + Logger.LogError(ex, "Error getting channel list"); if (enableCache) { @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.Error("Error getting channels", ex); + Logger.LogError(ex, "Error getting channels"); } } } @@ -201,7 +201,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.Error("Error getting channels", ex); + Logger.LogError(ex, "Error getting channels"); } } @@ -216,12 +216,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts var startTime = DateTime.UtcNow; await liveStream.Open(cancellationToken).ConfigureAwait(false); var endTime = DateTime.UtcNow; - Logger.Info("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); + Logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); return liveStream; } catch (Exception ex) { - Logger.Error("Error opening tuner", ex); + Logger.LogError(ex, "Error opening tuner"); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index e873eb8e9..be090df0c 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -303,7 +303,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } catch (Exception ex) { - Logger.ErrorException("Error getting tuner info", ex); + Logger.LogError(ex, "Error getting tuner info"); } } @@ -581,7 +581,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { var profile = streamId.Split('_')[0]; - Logger.Info("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile); + Logger.LogInformation("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile); var hdhrId = GetHdHrIdFromChannelId(channelInfo.Id); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 2bc5a0ed3..0e84622bd 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -6,7 +6,7 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Controller.LiveTv; using System.Net; @@ -244,7 +244,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun private async Task ReleaseLockkey(ISocket tcpClient, uint lockKeyValue) { - _logger.Info("HdHomerunManager.ReleaseLockkey {0}", lockKeyValue); + _logger.LogInformation("HdHomerunManager.ReleaseLockkey {0}", lockKeyValue); var ipEndPoint = new IpEndPointInfo(_remoteIp, HdHomeRunPort); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 33103979e..c781bccbb 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.System; using MediaBrowser.Model.LiveTv; @@ -56,7 +56,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); - Logger.Info("Opening HDHR UDP Live stream from {0}", uri.Host); + Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host); var remoteAddress = IPAddress.Parse(uri.Host); var embyRemoteAddress = _networkManager.ParseIpAddress(uri.Host); @@ -69,9 +69,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun localAddress = ((IPEndPoint)tcpSocket.LocalEndPoint).Address; tcpSocket.Close(); } - catch (Exception) + catch (Exception ex) { - Logger.Error("Unable to determine local ip address for Legacy HDHomerun stream."); + Logger.LogError(ex, "Unable to determine local ip address for Legacy HDHomerun stream."); return; } } @@ -87,21 +87,19 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun catch (Exception ex) { using (udpClient) + using (hdHomerunManager) { - using (hdHomerunManager) + if (!(ex is OperationCanceledException)) { - if (!(ex is OperationCanceledException)) - { - Logger.ErrorException("Error opening live stream:", ex); - } - throw; + Logger.LogError(ex, "Error opening live stream:"); } + throw; } } var taskCompletionSource = new TaskCompletionSource(); - StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token); + await StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token); //OpenedMediaSource.Protocol = MediaProtocol.File; //OpenedMediaSource.Path = tempFile; @@ -122,26 +120,24 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return Task.Run(async () => { using (udpClient) + using (hdHomerunManager) { - using (hdHomerunManager) + try { - try - { - await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException ex) - { - Logger.Info("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); - openTaskCompletionSource.TrySetException(ex); - } - catch (Exception ex) - { - Logger.ErrorException("Error opening live stream:", ex); - openTaskCompletionSource.TrySetException(ex); - } - - EnableStreamSharing = false; + await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false); } + catch (OperationCanceledException ex) + { + Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); + openTaskCompletionSource.TrySetException(ex); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error opening live stream:"); + openTaskCompletionSource.TrySetException(ex); + } + + EnableStreamSharing = false; } await DeleteTempFiles(new List { TempFilePath }).ConfigureAwait(false); @@ -166,30 +162,28 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var resolved = false; using (var source = _socketFactory.CreateNetworkStream(udpClient, false)) + using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) { - using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) + var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token; + + while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0) { - var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token; + cancellationToken.ThrowIfCancellationRequested(); - while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0) + currentCancellationToken = cancellationToken; + + read -= RtpHeaderBytes; + + if (read > 0) { - cancellationToken.ThrowIfCancellationRequested(); + fileStream.Write(buffer, RtpHeaderBytes, read); + } - currentCancellationToken = cancellationToken; - - read -= RtpHeaderBytes; - - if (read > 0) - { - fileStream.Write(buffer, RtpHeaderBytes, read); - } - - if (!resolved) - { - resolved = true; - DateOpened = DateTime.UtcNow; - Resolve(openTaskCompletionSource); - } + if (!resolved) + { + resolved = true; + DateOpened = DateTime.UtcNow; + Resolve(openTaskCompletionSource); } } } @@ -346,4 +340,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index 7e0ac4131..4a2b4ebb2 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.IO; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.LiveTv; using System.Linq; @@ -75,7 +75,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { EnableStreamSharing = false; - Logger.Info("Closing " + GetType().Name); + Logger.LogInformation("Closing " + GetType().Name); LiveStreamCancellationTokenSource.Cancel(); @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error closing live stream", ex); + Logger.LogError(ex, "Error closing live stream"); } } @@ -120,7 +120,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { if (retryCount == 0) { - Logger.Info("Deleting temp files {0}", string.Join(", ", paths.ToArray())); + Logger.LogInformation("Deleting temp files {0}", string.Join(", ", paths.ToArray())); } var failedFiles = new List(); @@ -139,7 +139,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - //Logger.ErrorException("Error deleting file {0}", ex, path); + Logger.LogError(ex, "Error deleting file {path}", path); failedFiles.Add(path); } } @@ -181,14 +181,14 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts isLastFile = nextFileInfo.Item2; } - Logger.Info("Live Stream ended."); + Logger.LogInformation("Live Stream ended."); } private Tuple GetNextFile(string currentFile) { var files = GetStreamFilePaths(); - //Logger.Info("Live stream files: {0}", string.Join(", ", files.ToArray())); + //logger.LogInformation("Live stream files: {0}", string.Join(", ", files.ToArray())); if (string.IsNullOrEmpty(currentFile)) { @@ -204,7 +204,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken) { - //Logger.Info("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit); + //logger.LogInformation("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit); using (var inputStream = (FileStream)GetInputStream(path, allowAsync)) { @@ -227,7 +227,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts private void TrySeek(FileStream stream, long offset) { - //Logger.Info("TrySeek live stream"); + //logger.LogInformation("TrySeek live stream"); try { stream.Seek(offset, SeekOrigin.End); @@ -242,7 +242,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error seeking stream", ex); + Logger.LogError(ex, "Error seeking stream"); } } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index a1bff2b5b..a54bd1613 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; @@ -205,4 +205,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts return Task.FromResult(new List()); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index ca744b615..208225c1e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -12,7 +12,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Extensions; namespace Emby.Server.Implementations.LiveTv.TunerHosts @@ -88,7 +88,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts if (line.StartsWith(ExtInfPrefix, StringComparison.OrdinalIgnoreCase)) { extInf = line.Substring(ExtInfPrefix.Length).Trim(); - _logger.Info("Found m3u channel: {0}", extInf); + _logger.LogInformation("Found m3u channel: {0}", extInf); } else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith("#", StringComparison.OrdinalIgnoreCase)) { @@ -335,4 +335,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts return dict; } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 572edb167..9b10daba0 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -9,7 +9,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.System; using System.Globalization; @@ -44,7 +44,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); var typeName = GetType().Name; - Logger.Info("Opening " + typeName + " Live stream from {0}", url); + Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url); var httpRequestOptions = new HttpRequestOptions { @@ -125,17 +125,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { try { + Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath); using (response) + using (var stream = response.Content) + using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) { - using (var stream = response.Content) - { - Logger.Info("Beginning {0} stream to {1}", GetType().Name, TempFilePath); - - using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) - { - await ApplicationHost.StreamHelper.CopyToAsync(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false); - } - } + await ApplicationHost.StreamHelper.CopyToAsync(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) @@ -143,7 +138,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error copying live stream.", ex); + Logger.LogError(ex, "Error copying live stream."); } EnableStreamSharing = false; await DeleteTempFiles(new List { TempFilePath }).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 71a4ca824..c6de9d957 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -10,7 +10,7 @@ using System.Globalization; using System.IO; using System.Linq; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Reflection; namespace Emby.Server.Implementations.Localization @@ -82,7 +82,7 @@ namespace Emby.Server.Implementations.Localization using (var stream = _assemblyInfo.GetManifestResourceStream(type, resource)) { var target = Path.Combine(localizationPath, filename); - _logger.Info("Extracting ratings to {0}", target); + _logger.LogInformation("Extracting ratings to {0}", target); using (var fs = _fileSystem.GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) { diff --git a/Emby.Server.Implementations/Logging/ConsoleLogger.cs b/Emby.Server.Implementations/Logging/ConsoleLogger.cs deleted file mode 100644 index 51199f08a..000000000 --- a/Emby.Server.Implementations/Logging/ConsoleLogger.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using MediaBrowser.Model.Logging; - -namespace Emby.Server.Implementations.Logging -{ - public class ConsoleLogger : IConsoleLogger - { - public void WriteLine(string message) - { - Console.WriteLine(message); - } - } -} diff --git a/Emby.Server.Implementations/Logging/SimpleLogManager.cs b/Emby.Server.Implementations/Logging/SimpleLogManager.cs deleted file mode 100644 index 390814c34..000000000 --- a/Emby.Server.Implementations/Logging/SimpleLogManager.cs +++ /dev/null @@ -1,360 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.Logging; - -namespace Emby.Server.Implementations.Logging -{ - public class SimpleLogManager : ILogManager, IDisposable - { - public LogSeverity LogSeverity { get; set; } - public string ExceptionMessagePrefix { get; set; } - private FileLogger _fileLogger; - - private readonly string LogDirectory; - private readonly string LogFilePrefix; - public string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; - - public SimpleLogManager(string logDirectory, string logFileNamePrefix) - { - LogDirectory = logDirectory; - LogFilePrefix = logFileNamePrefix; - } - - public ILogger GetLogger(string name) - { - return new NamedLogger(name, this); - } - - public async Task ReloadLogger(LogSeverity severity, CancellationToken cancellationToken) - { - LogSeverity = severity; - - var logger = _fileLogger; - if (logger != null) - { - logger.Dispose(); - await TryMoveToArchive(logger.Path, cancellationToken).ConfigureAwait(false); - } - - var newPath = Path.Combine(LogDirectory, LogFilePrefix + ".txt"); - - if (File.Exists(newPath)) - { - newPath = await TryMoveToArchive(newPath, cancellationToken).ConfigureAwait(false); - } - - _fileLogger = new FileLogger(newPath); - - if (LoggerLoaded != null) - { - try - { - LoggerLoaded(this, EventArgs.Empty); - } - catch (Exception ex) - { - GetLogger("Logger").ErrorException("Error in LoggerLoaded event", ex); - } - } - } - - private async Task TryMoveToArchive(string file, CancellationToken cancellationToken, int retryCount = 0) - { - var archivePath = GetArchiveFilePath(); - - try - { - File.Move(file, archivePath); - - return file; - } - catch (FileNotFoundException) - { - return file; - } - catch (DirectoryNotFoundException) - { - return file; - } - catch - { - if (retryCount >= 50) - { - return GetArchiveFilePath(); - } - - await Task.Delay(100, cancellationToken).ConfigureAwait(false); - - return await TryMoveToArchive(file, cancellationToken, retryCount + 1).ConfigureAwait(false); - } - } - - private string GetArchiveFilePath() - { - return Path.Combine(LogDirectory, LogFilePrefix + "-" + decimal.Floor(DateTime.Now.Ticks / 10000000) + ".txt"); - } - - public event EventHandler LoggerLoaded; - - public void Flush() - { - var logger = _fileLogger; - if (logger != null) - { - logger.Flush(); - } - } - - private bool _console = true; - public void AddConsoleOutput() - { - _console = true; - } - - public void RemoveConsoleOutput() - { - _console = false; - } - - public void Log(string message) - { - if (_console) - { - Console.WriteLine(message); - } - - var logger = _fileLogger; - if (logger != null) - { - message = DateTime.Now.ToString(DateTimeFormat) + " " + message; - - logger.Log(message); - } - } - - public void Dispose() - { - var logger = _fileLogger; - if (logger != null) - { - logger.Dispose(); - - var task = TryMoveToArchive(logger.Path, CancellationToken.None); - Task.WaitAll(task); - } - - _fileLogger = null; - } - } - - public class FileLogger : IDisposable - { - private readonly FileStream _fileStream; - - private bool _disposed; - private readonly CancellationTokenSource _cancellationTokenSource; - private readonly BlockingCollection _queue = new BlockingCollection(); - - public string Path { get; set; } - - public FileLogger(string path) - { - Path = path; - - Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)); - - _fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 32768); - _cancellationTokenSource = new CancellationTokenSource(); - - Task.Factory.StartNew(LogInternal, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); - } - - private void LogInternal() - { - while (!_cancellationTokenSource.IsCancellationRequested && !_disposed) - { - try - { - foreach (var message in _queue.GetConsumingEnumerable()) - { - var bytes = Encoding.UTF8.GetBytes(message + Environment.NewLine); - if (_disposed) - { - return; - } - - _fileStream.Write(bytes, 0, bytes.Length); - if (_disposed) - { - return; - } - - _fileStream.Flush(true); - } - } - catch - { - - } - } - } - - public void Log(string message) - { - if (_disposed) - { - return; - } - - _queue.Add(message); - } - - public void Flush() - { - if (_disposed) - { - return; - } - - _fileStream.Flush(true); - } - - public void Dispose() - { - if (_disposed) - { - return; - } - - _disposed = true; - _cancellationTokenSource.Cancel(); - - var stream = _fileStream; - if (stream != null) - { - using (stream) - { - stream.Flush(true); - } - } - } - } - - public class NamedLogger : ILogger - { - public string Name { get; private set; } - private readonly SimpleLogManager _logManager; - - public NamedLogger(string name, SimpleLogManager logManager) - { - Name = name; - _logManager = logManager; - } - - public void Info(string message, params object[] paramList) - { - Log(LogSeverity.Info, message, paramList); - } - - public void Error(string message, params object[] paramList) - { - Log(LogSeverity.Error, message, paramList); - } - - public void Warn(string message, params object[] paramList) - { - Log(LogSeverity.Warn, message, paramList); - } - - public void Debug(string message, params object[] paramList) - { - if (_logManager.LogSeverity == LogSeverity.Info) - { - return; - } - Log(LogSeverity.Debug, message, paramList); - } - - public void Fatal(string message, params object[] paramList) - { - Log(LogSeverity.Fatal, message, paramList); - } - - public void FatalException(string message, Exception exception, params object[] paramList) - { - ErrorException(message, exception, paramList); - } - - public void ErrorException(string message, Exception exception, params object[] paramList) - { - LogException(LogSeverity.Error, message, exception, paramList); - } - - private void LogException(LogSeverity level, string message, Exception exception, params object[] paramList) - { - message = FormatMessage(message, paramList).Replace(Environment.NewLine, ". "); - - var messageText = LogHelper.GetLogMessage(exception); - - var prefix = _logManager.ExceptionMessagePrefix; - - if (!string.IsNullOrWhiteSpace(prefix)) - { - messageText.Insert(0, prefix); - } - - LogMultiline(message, level, messageText); - } - - private static string FormatMessage(string message, params object[] paramList) - { - if (paramList != null) - { - for (var i = 0; i < paramList.Length; i++) - { - var obj = paramList[i]; - - message = message.Replace("{" + i + "}", (obj == null ? "null" : obj.ToString())); - } - } - - return message; - } - - public void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent) - { - if (severity == LogSeverity.Debug && _logManager.LogSeverity == LogSeverity.Info) - { - return; - } - - additionalContent.Insert(0, message + Environment.NewLine); - - const char tabChar = '\t'; - - var text = additionalContent.ToString() - .Replace(Environment.NewLine, Environment.NewLine + tabChar) - .TrimEnd(tabChar); - - if (text.EndsWith(Environment.NewLine)) - { - text = text.Substring(0, text.LastIndexOf(Environment.NewLine, StringComparison.OrdinalIgnoreCase)); - } - - Log(severity, text); - } - - public void Log(LogSeverity severity, string message, params object[] paramList) - { - message = severity + " " + Name + ": " + FormatMessage(message, paramList); - - _logManager.Log(message); - } - } -} diff --git a/Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs b/Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs deleted file mode 100644 index 7104935e1..000000000 --- a/Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs +++ /dev/null @@ -1,45 +0,0 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Logging; -using System; -using System.IO; -using MediaBrowser.Model.IO; - -namespace Emby.Server.Implementations.Logging -{ - public class UnhandledExceptionWriter - { - private readonly IApplicationPaths _appPaths; - private readonly ILogger _logger; - private readonly ILogManager _logManager; - private readonly IFileSystem _fileSystem; - private readonly IConsoleLogger _console; - - public UnhandledExceptionWriter(IApplicationPaths appPaths, ILogger logger, ILogManager logManager, IFileSystem fileSystem, IConsoleLogger console) - { - _appPaths = appPaths; - _logger = logger; - _logManager = logManager; - _fileSystem = fileSystem; - _console = console; - } - - public void Log(Exception ex) - { - _logger.ErrorException("UnhandledException", ex); - _logManager.Flush(); - - var path = Path.Combine(_appPaths.LogDirectoryPath, "unhandled_" + Guid.NewGuid() + ".txt"); - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); - - var builder = LogHelper.GetLogMessage(ex); - - // Write to console just in case file logging fails - _console.WriteLine("UnhandledException"); - - var logMessage = builder.ToString(); - _console.WriteLine(logMessage); - - _fileSystem.WriteAllText(path, logMessage); - } - } -} diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs index c6033b4f4..792ffb3c4 100644 --- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; @@ -123,7 +123,7 @@ namespace Emby.Server.Implementations.MediaEncoder { if (chapter.StartPositionTicks >= runtimeTicks) { - _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name); + _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name); break; } @@ -166,7 +166,7 @@ namespace Emby.Server.Implementations.MediaEncoder } catch (Exception ex) { - _logger.ErrorException("Error extracting chapter images for {0}", ex, string.Join(",", video.Path)); + _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(",", video.Path)); success = false; break; } @@ -226,7 +226,7 @@ namespace Emby.Server.Implementations.MediaEncoder foreach (var image in deadImages) { - _logger.Debug("Deleting dead chapter image {0}", image); + _logger.LogDebug("Deleting dead chapter image {path}", image); try { @@ -234,7 +234,7 @@ namespace Emby.Server.Implementations.MediaEncoder } catch (IOException ex) { - _logger.ErrorException("Error deleting {0}.", ex, image); + _logger.LogError(ex, "Error deleting {path}.", image); } } } diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index 9726ef097..3f93e767f 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -3,7 +3,7 @@ using System.IO; using System.Net; using System.Net.Sockets; using Emby.Server.Implementations.Networking; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; namespace Emby.Server.Implementations.Net diff --git a/Emby.Server.Implementations/Networking/NetworkManager.cs b/Emby.Server.Implementations/Networking/NetworkManager.cs index 20abaf27c..260d20e35 100644 --- a/Emby.Server.Implementations/Networking/NetworkManager.cs +++ b/Emby.Server.Implementations/Networking/NetworkManager.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using System.Numerics; @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error binding to NetworkAddressChanged event", ex); + Logger.LogError(ex, "Error binding to NetworkAddressChanged event"); } try @@ -45,20 +45,20 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error binding to NetworkChange_NetworkAvailabilityChanged event", ex); + Logger.LogError(ex, "Error binding to NetworkChange_NetworkAvailabilityChanged event"); } } } private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) { - Logger.Debug("NetworkAvailabilityChanged"); + Logger.LogDebug("NetworkAvailabilityChanged"); OnNetworkChanged(); } private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e) { - Logger.Debug("NetworkAddressChanged"); + Logger.LogDebug("NetworkAddressChanged"); OnNetworkChanged(); } @@ -189,7 +189,7 @@ namespace Emby.Server.Implementations.Networking foreach (var subnet_Match in subnets) { - //Logger.Debug("subnet_Match:" + subnet_Match); + //logger.LogDebug("subnet_Match:" + subnet_Match); if (endpoint.StartsWith(subnet_Match + ".", StringComparison.OrdinalIgnoreCase)) { @@ -355,13 +355,13 @@ namespace Emby.Server.Implementations.Networking try { var host = uri.DnsSafeHost; - Logger.Debug("Resolving host {0}", host); + Logger.LogDebug("Resolving host {0}", host); address = GetIpAddresses(host).Result.FirstOrDefault(); if (address != null) { - Logger.Debug("{0} resolved to {1}", host, address); + Logger.LogDebug("{0} resolved to {1}", host, address); return IsInLocalNetworkInternal(address.ToString(), false); } @@ -372,7 +372,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error resovling hostname", ex); + Logger.LogError(ex, "Error resolving hostname"); } } } @@ -399,7 +399,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error in GetAllNetworkInterfaces", ex); + Logger.LogError(ex, "Error in GetAllNetworkInterfaces"); return new List(); } @@ -409,7 +409,7 @@ namespace Emby.Server.Implementations.Networking try { // suppress logging because it might be causing nas device wake up - //Logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); + //logger.LogDebug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); var ipProperties = network.GetIPProperties(); @@ -428,7 +428,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error querying network interface", ex); + Logger.LogError(ex, "Error querying network interface"); return new List(); } @@ -706,7 +706,7 @@ namespace Emby.Server.Implementations.Networking public async Task GetHostAddressesAsync(string host) { var addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false); - return addresses.Select(ToIpAddressInfo).ToArray(addresses.Length); + return addresses.Select(ToIpAddressInfo).ToArray(); } /// diff --git a/Emby.Server.Implementations/News/NewsEntryPoint.cs b/Emby.Server.Implementations/News/NewsEntryPoint.cs index 38a250593..ce6fe6630 100644 --- a/Emby.Server.Implementations/News/NewsEntryPoint.cs +++ b/Emby.Server.Implementations/News/NewsEntryPoint.cs @@ -4,7 +4,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Notifications; using MediaBrowser.Controller.Plugins; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.News; using MediaBrowser.Model.Notifications; using MediaBrowser.Model.Serialization; @@ -67,7 +67,7 @@ namespace Emby.Server.Implementations.News } catch (Exception ex) { - _logger.ErrorException("Error downloading news", ex); + _logger.LogError(ex, "Error downloading news"); } } diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs index e0a6f56ec..470711b9e 100644 --- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs +++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Playlists; using System; using System.Collections.Generic; @@ -136,7 +136,7 @@ namespace Emby.Server.Implementations.Playlists parentFolder.AddChild(playlist, CancellationToken.None); - await playlist.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) { ForceSave = true }, CancellationToken.None) + await playlist.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true }, CancellationToken.None) .ConfigureAwait(false); if (options.ItemIdList.Length > 0) @@ -208,7 +208,7 @@ namespace Emby.Server.Implementations.Playlists var newList = playlist.LinkedChildren.ToList(); newList.AddRange(list); - playlist.LinkedChildren = newList.ToArray(newList.Count); + playlist.LinkedChildren = newList.ToArray(); playlist.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None); @@ -217,7 +217,7 @@ namespace Emby.Server.Implementations.Playlists SavePlaylistFile(playlist); } - _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true @@ -250,7 +250,7 @@ namespace Emby.Server.Implementations.Playlists SavePlaylistFile(playlist); } - _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true @@ -290,7 +290,7 @@ namespace Emby.Server.Implementations.Playlists newList.Insert(newIndex, item); } - playlist.LinkedChildren = newList.ToArray(newList.Count); + playlist.LinkedChildren = newList.ToArray(); playlist.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None); diff --git a/Emby.Server.Implementations/ResourceFileManager.cs b/Emby.Server.Implementations/ResourceFileManager.cs index ce29b52f6..04cf0632c 100644 --- a/Emby.Server.Implementations/ResourceFileManager.cs +++ b/Emby.Server.Implementations/ResourceFileManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - _logger.ErrorException("Error in Path.GetFullPath", ex); + _logger.LogError(ex, "Error in Path.GetFullPath"); } // Don't allow file system access outside of the source folder diff --git a/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs index 7a5efded3..09dcc320a 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Persistence; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -44,9 +44,9 @@ namespace Emby.Server.Implementations.ScheduledTasks /// /// Initializes a new instance of the class. /// - public ChapterImagesTask(ILogManager logManager, ILibraryManager libraryManager, IItemRepository itemRepo, IApplicationPaths appPaths, IEncodingManager encodingManager, IFileSystem fileSystem) + public ChapterImagesTask(ILoggerFactory loggerFactory, ILibraryManager libraryManager, IItemRepository itemRepo, IApplicationPaths appPaths, IEncodingManager encodingManager, IFileSystem fileSystem) { - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _libraryManager = libraryManager; _itemRepo = itemRepo; _appPaths = appPaths; @@ -121,7 +121,7 @@ namespace Emby.Server.Implementations.ScheduledTasks previouslyFailedImages = new List(); } - var directoryService = new DirectoryService(_fileSystem); + var directoryService = new DirectoryService(_logger, _fileSystem); foreach (var video in videos) { @@ -145,7 +145,7 @@ namespace Emby.Server.Implementations.ScheduledTasks _fileSystem.CreateDirectory(parentPath); - _fileSystem.WriteAllText(failHistoryPath, string.Join("|", previouslyFailedImages.ToArray(previouslyFailedImages.Count))); + _fileSystem.WriteAllText(failHistoryPath, string.Join("|", previouslyFailedImages.ToArray())); } numComplete++; diff --git a/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs index a2779c7cd..afcee02e5 100644 --- a/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs @@ -2,7 +2,7 @@ using System.Globalization; using System.Threading; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks @@ -45,7 +45,7 @@ namespace Emby.Server.Implementations.ScheduledTasks var dueTime = triggerDate - now; - logger.Info("Daily trigger for {0} set to fire at {1}, which is {2} minutes from now.", taskName, triggerDate.ToString(), dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + logger.LogInformation("Daily trigger for {0} set to fire at {1}, which is {2} minutes from now.", taskName, triggerDate.ToString(), dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); Timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1)); } diff --git a/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs index dcccb252a..5f6a0dfe6 100644 --- a/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs @@ -2,7 +2,7 @@ using System.Linq; using System.Threading; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks diff --git a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs index 691112638..46a7f1f27 100644 --- a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs @@ -1,6 +1,6 @@ using MediaBrowser.Common; using MediaBrowser.Common.Updates; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using System; using System.Collections.Generic; @@ -89,11 +89,11 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (HttpException ex) { - _logger.ErrorException("Error downloading {0}", ex, package.name); + _logger.LogError(ex, "Error downloading {name}", package.name); } catch (IOException ex) { - _logger.ErrorException("Error updating {0}", ex, package.name); + _logger.LogError(ex, "Error updating {name}", package.name); } // Update progress @@ -139,4 +139,4 @@ namespace Emby.Server.Implementations.ScheduledTasks public bool IsLogged => true; } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index f6397b670..7c2ce4af3 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -9,9 +9,8 @@ using MediaBrowser.Common.Events; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Progress; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; @@ -147,7 +146,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (Exception ex) { - Logger.ErrorException("Error deserializing {0}", ex, path); + Logger.LogError(ex, "Error deserializing {path}", path); } _readFromFile = true; } @@ -276,7 +275,7 @@ namespace Emby.Server.Implementations.ScheduledTasks get { var triggers = InternalTriggers; - return triggers.Select(i => i.Item1).ToArray(triggers.Length); + return triggers.Select(i => i.Item1).ToArray(); } set { @@ -290,7 +289,7 @@ namespace Emby.Server.Implementations.ScheduledTasks SaveTriggers(triggerList); - InternalTriggers = triggerList.Select(i => new Tuple(i, GetTrigger(i))).ToArray(triggerList.Length); + InternalTriggers = triggerList.Select(i => new Tuple(i, GetTrigger(i))).ToArray(); } } @@ -361,7 +360,7 @@ namespace Emby.Server.Implementations.ScheduledTasks return; } - Logger.Info("{0} fired for task: {1}", trigger.GetType().Name, Name); + Logger.LogInformation("{0} fired for task: {1}", trigger.GetType().Name, Name); trigger.Stop(); @@ -409,7 +408,7 @@ namespace Emby.Server.Implementations.ScheduledTasks CurrentCancellationTokenSource = new CancellationTokenSource(); - Logger.Info("Executing {0}", Name); + Logger.LogInformation("Executing {0}", Name); ((TaskManager)TaskManager).OnTaskExecuting(this); @@ -437,7 +436,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (Exception ex) { - Logger.ErrorException("Error", ex); + Logger.LogError(ex, "Error"); failureException = ex; @@ -494,7 +493,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { if (State == TaskState.Running) { - Logger.Info("Attempting to cancel Scheduled Task {0}", Name); + Logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name); CurrentCancellationTokenSource.Cancel(); } } @@ -615,7 +614,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { var elapsedTime = endTime - startTime; - Logger.Info("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds); + Logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds); var result = new TaskResult { @@ -665,12 +664,12 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - Logger.Info(Name + ": Cancelling"); + Logger.LogInformation(Name + ": Cancelling"); token.Cancel(); } catch (Exception ex) { - Logger.ErrorException("Error calling CancellationToken.Cancel();", ex); + Logger.LogError(ex, "Error calling CancellationToken.Cancel();"); } } var task = _currentTask; @@ -678,21 +677,21 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - Logger.Info(Name + ": Waiting on Task"); + Logger.LogInformation(Name + ": Waiting on Task"); var exited = Task.WaitAll(new[] { task }, 2000); if (exited) { - Logger.Info(Name + ": Task exited"); + Logger.LogInformation(Name + ": Task exited"); } else { - Logger.Info(Name + ": Timed out waiting for task to stop"); + Logger.LogInformation(Name + ": Timed out waiting for task to stop"); } } catch (Exception ex) { - Logger.ErrorException("Error calling Task.WaitAll();", ex); + Logger.LogError(ex, "Error calling Task.WaitAll();"); } } @@ -700,12 +699,12 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - Logger.Debug(Name + ": Disposing CancellationToken"); + Logger.LogDebug(Name + ": Disposing CancellationToken"); token.Dispose(); } catch (Exception ex) { - Logger.ErrorException("Error calling CancellationToken.Dispose();", ex); + Logger.LogError(ex, "Error calling CancellationToken.Dispose();"); } } if (wassRunning) diff --git a/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs index 20a4304cc..35366a044 100644 --- a/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks diff --git a/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs index c4623bf5b..def142f88 100644 --- a/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; diff --git a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs index 0c9eb0f1b..4cb97cbda 100644 --- a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs @@ -1,6 +1,6 @@ using MediaBrowser.Common; using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading; @@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.ScheduledTasks if (!updateInfo.IsUpdateAvailable) { - Logger.Debug("No application update available."); + Logger.LogDebug("No application update available."); return; } @@ -83,13 +83,13 @@ namespace Emby.Server.Implementations.ScheduledTasks if (ConfigurationManager.CommonConfiguration.EnableAutoUpdate) { - Logger.Info("Update Revision {0} available. Updating...", updateInfo.AvailableVersion); + Logger.LogInformation("Update Revision {0} available. Updating...", updateInfo.AvailableVersion); await _appHost.UpdateApplication(updateInfo.Package, cancellationToken, progress).ConfigureAwait(false); } else { - Logger.Info("A new version of " + _appHost.Name + " is available."); + Logger.LogInformation("A new version of " + _appHost.Name + " is available."); } } diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs index 8963693ab..0322583dc 100644 --- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs +++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs @@ -7,7 +7,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; using MediaBrowser.Model.Events; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; @@ -185,7 +185,7 @@ namespace Emby.Server.Implementations.ScheduledTasks if (scheduledTask == null) { - Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name); + Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name); } else { @@ -217,13 +217,13 @@ namespace Emby.Server.Implementations.ScheduledTasks if (scheduledTask == null) { - Logger.Error("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name); + Logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name); } else { var type = scheduledTask.ScheduledTask.GetType(); - Logger.Info("Queueing task {0}", type.Name); + Logger.LogInformation("Queueing task {0}", type.Name); lock (_taskQueue) { @@ -246,7 +246,7 @@ namespace Emby.Server.Implementations.ScheduledTasks if (scheduledTask == null) { - Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name); + Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name); } else { @@ -263,7 +263,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { var type = task.ScheduledTask.GetType(); - Logger.Info("Queueing task {0}", type.Name); + Logger.LogInformation("Queueing task {0}", type.Name); lock (_taskQueue) { @@ -360,7 +360,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// private void ExecuteQueuedTasks() { - Logger.Info("ExecuteQueuedTasks"); + Logger.LogInformation("ExecuteQueuedTasks"); // Execute queued tasks lock (_taskQueue) diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs index 05fb08447..c60f59ce4 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs @@ -6,7 +6,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks.Tasks @@ -132,11 +132,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.ErrorException("Error deleting directory {0}", ex, directory); + _logger.LogError(ex, "Error deleting directory {path}", directory); } catch (IOException ex) { - _logger.ErrorException("Error deleting directory {0}", ex, directory); + _logger.LogError(ex, "Error deleting directory {path}", directory); } } } @@ -150,11 +150,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.ErrorException("Error deleting file {0}", ex, path); + _logger.LogError(ex, "Error deleting file {path}", path); } catch (IOException ex) { - _logger.ErrorException("Error deleting file {0}", ex, path); + _logger.LogError(ex, "Error deleting file {path}", path); } } diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs deleted file mode 100644 index fbc3a309e..000000000 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Tasks; - -namespace Emby.Server.Implementations.ScheduledTasks.Tasks -{ - /// - /// Class ReloadLoggerFileTask - /// - public class ReloadLoggerFileTask : IScheduledTask, IConfigurableScheduledTask - { - /// - /// Gets or sets the log manager. - /// - /// The log manager. - private ILogManager LogManager { get; set; } - /// - /// Gets or sets the configuration manager. - /// - /// The configuration manager. - private IConfigurationManager ConfigurationManager { get; set; } - - /// - /// Initializes a new instance of the class. - /// - /// The logManager. - /// The configuration manager. - public ReloadLoggerFileTask(ILogManager logManager, IConfigurationManager configurationManager) - { - LogManager = logManager; - ConfigurationManager = configurationManager; - } - - /// - /// Gets the default triggers. - /// - /// IEnumerable{BaseTaskTrigger}. - public IEnumerable GetDefaultTriggers() - { - var trigger = new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerDaily, TimeOfDayTicks = TimeSpan.FromHours(0).Ticks }; //12am - - return new[] { trigger }; - } - - /// - /// Executes the internal. - /// - /// The cancellation token. - /// The progress. - /// Task. - public Task Execute(CancellationToken cancellationToken, IProgress progress) - { - cancellationToken.ThrowIfCancellationRequested(); - - progress.Report(0); - - return LogManager.ReloadLogger(ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging - ? LogSeverity.Debug - : LogSeverity.Info, cancellationToken); - } - - /// - /// Gets the name. - /// - /// The name. - public string Name - { - get { return "Rotate log file"; } - } - - public string Key { get; } - - /// - /// Gets the description. - /// - /// The description. - public string Description - { - get { return "Moves logging to a new file to help reduce log file sizes."; } - } - - /// - /// Gets the category. - /// - /// The category. - public string Category - { - get { return "Application"; } - } - - public bool IsHidden - { - get { return false; } - } - - public bool IsEnabled - { - get { return true; } - } - - public bool IsLogged - { - get { return true; } - } - } -} diff --git a/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs index 82b449917..e694e0855 100644 --- a/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs @@ -1,7 +1,7 @@ using System; using System.Threading; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs index 45f7f1e95..228d511ce 100644 --- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs +++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs @@ -7,7 +7,7 @@ using System.Threading; using Emby.Server.Implementations.Data; using MediaBrowser.Controller; using MediaBrowser.Controller.Security; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using SQLitePCL.pretty; using MediaBrowser.Model.Extensions; @@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.Security } catch (Exception ex) { - Logger.ErrorException("Error migrating authentication database", ex); + Logger.LogError(ex, "Error migrating authentication database"); } } @@ -241,7 +241,7 @@ namespace Emby.Server.Implementations.Security var whereTextWithoutPaging = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); + " where " + string.Join(" AND ", whereClauses.ToArray()); commandText += whereTextWithoutPaging; @@ -298,7 +298,7 @@ namespace Emby.Server.Implementations.Security } } - result.Items = list.ToArray(list.Count); + result.Items = list.ToArray(); return result; }, ReadTransactionMode); diff --git a/Emby.Server.Implementations/Security/PluginSecurityManager.cs b/Emby.Server.Implementations/Security/PluginSecurityManager.cs index 8d8d6700e..2b1494c39 100644 --- a/Emby.Server.Implementations/Security/PluginSecurityManager.cs +++ b/Emby.Server.Implementations/Security/PluginSecurityManager.cs @@ -12,7 +12,7 @@ using MediaBrowser.Controller; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; @@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.Security /// Initializes a new instance of the class. /// public PluginSecurityManager(IServerApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer, - IApplicationPaths appPaths, ILogManager logManager, IFileSystem fileSystem, ICryptoProvider cryptographyProvider) + IApplicationPaths appPaths, ILoggerFactory loggerFactory, IFileSystem fileSystem, ICryptoProvider cryptographyProvider) { if (httpClient == null) { @@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.Security _appPaths = appPaths; _fileSystem = fileSystem; _cryptographyProvider = cryptographyProvider; - _logger = logManager.GetLogger("SecurityManager"); + _logger = loggerFactory.CreateLogger("SecurityManager"); } /// @@ -135,7 +135,7 @@ namespace Emby.Server.Implementations.Security if (reg == null) { var msg = "Result from appstore registration was null."; - _logger.Error(msg); + _logger.LogError(msg); throw new ArgumentException(msg); } if (!String.IsNullOrEmpty(reg.key)) @@ -150,18 +150,15 @@ namespace Emby.Server.Implementations.Security SaveAppStoreInfo(parameters); throw; } - catch (HttpException e) + catch (HttpException ex) { - _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); + _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT"); - if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.PaymentRequired) - { - } throw new Exception("Error registering store sale"); } - catch (Exception e) + catch (Exception ex) { - _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); + _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT"); SaveAppStoreInfo(parameters); //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually. throw new Exception("Error registering store sale"); diff --git a/Emby.Server.Implementations/Serialization/JsonSerializer.cs b/Emby.Server.Implementations/Serialization/JsonSerializer.cs index 26371d21d..423fe7b18 100644 --- a/Emby.Server.Implementations/Serialization/JsonSerializer.cs +++ b/Emby.Server.Implementations/Serialization/JsonSerializer.cs @@ -1,7 +1,7 @@ using System; using System.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System.Threading.Tasks; @@ -69,7 +69,7 @@ namespace Emby.Common.Implementations.Serialization private Stream OpenFile(string path) { - //_logger.Debug("Deserializing file {0}", path); + //_logger.LogDebug("Deserializing file {0}", path); return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072); } diff --git a/Emby.Server.Implementations/Serialization/XmlSerializer.cs b/Emby.Server.Implementations/Serialization/XmlSerializer.cs index e0603a01f..dfc324919 100644 --- a/Emby.Server.Implementations/Serialization/XmlSerializer.cs +++ b/Emby.Server.Implementations/Serialization/XmlSerializer.cs @@ -4,7 +4,7 @@ using System.IO; using System.Xml; using System.Xml.Serialization; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.Serialization @@ -90,7 +90,7 @@ namespace Emby.Server.Implementations.Serialization /// The file. public void SerializeToFile(object obj, string file) { - _logger.Debug("Serializing to file {0}", file); + _logger.LogDebug("Serializing to file {0}", file); using (var stream = new FileStream(file, FileMode.Create)) { SerializeToStream(obj, stream); @@ -105,7 +105,7 @@ namespace Emby.Server.Implementations.Serialization /// System.Object. public object DeserializeFromFile(Type type, string file) { - _logger.Debug("Deserializing file {0}", file); + _logger.LogDebug("Deserializing file {0}", file); using (var stream = _fileSystem.OpenRead(file)) { return DeserializeFromStream(type, stream); diff --git a/Emby.Server.Implementations/Services/ServiceController.cs b/Emby.Server.Implementations/Services/ServiceController.cs index 3726c9f6b..46af83128 100644 --- a/Emby.Server.Implementations/Services/ServiceController.cs +++ b/Emby.Server.Implementations/Services/ServiceController.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Emby.Server.Implementations.HttpServer; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; namespace Emby.Server.Implementations.Services @@ -99,7 +99,7 @@ namespace Emby.Server.Implementations.Services pathsAtFirstMatch.Add(restPath); } - public RestPath GetRestPathForRequest(string httpMethod, string pathInfo, ILogger logger) + public RestPath GetRestPathForRequest(string httpMethod, string pathInfo) { var matchUsingPathParts = RestPath.GetPathPartsForMatching(pathInfo); @@ -117,7 +117,7 @@ namespace Emby.Server.Implementations.Services RestPath bestMatch = null; foreach (var restPath in firstMatches) { - var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger); + var score = restPath.MatchScore(httpMethod, matchUsingPathParts); if (score > bestScore) { bestScore = score; @@ -140,7 +140,7 @@ namespace Emby.Server.Implementations.Services RestPath bestMatch = null; foreach (var restPath in firstMatches) { - var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger); + var score = restPath.MatchScore(httpMethod, matchUsingPathParts); if (score > bestScore) { bestScore = score; @@ -183,4 +183,4 @@ namespace Emby.Server.Implementations.Services } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Services/ServiceExec.cs b/Emby.Server.Implementations/Services/ServiceExec.cs index 79b57438c..9516c1e38 100644 --- a/Emby.Server.Implementations/Services/ServiceExec.cs +++ b/Emby.Server.Implementations/Services/ServiceExec.cs @@ -181,7 +181,7 @@ namespace Emby.Server.Implementations.Services } if (reqFilters.Count > 0) - actionCtx.RequestFilters = reqFilters.OrderBy(i => i.Priority).ToArray(reqFilters.Count); + actionCtx.RequestFilters = reqFilters.OrderBy(i => i.Priority).ToArray(); actions.Add(actionCtx); } @@ -220,4 +220,4 @@ namespace Emby.Server.Implementations.Services } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Services/ServiceHandler.cs b/Emby.Server.Implementations/Services/ServiceHandler.cs index e76857a8d..f5fcb5fe6 100644 --- a/Emby.Server.Implementations/Services/ServiceHandler.cs +++ b/Emby.Server.Implementations/Services/ServiceHandler.cs @@ -4,7 +4,7 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; using Emby.Server.Implementations.HttpServer; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; namespace Emby.Server.Implementations.Services @@ -24,11 +24,11 @@ namespace Emby.Server.Implementations.Services return Task.FromResult(host.CreateInstance(requestType)); } - public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, ILogger logger, out string contentType) + public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, out string contentType) { pathInfo = GetSanitizedPathInfo(pathInfo, out contentType); - return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo, logger); + return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo); } public static string GetSanitizedPathInfo(string pathInfo, out string contentType) @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Services if (this.RestPath == null) { string contentType; - this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, new NullLogger(), out contentType); + this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, out contentType); if (contentType != null) ResponseContentType = contentType; diff --git a/Emby.Server.Implementations/Services/ServicePath.cs b/Emby.Server.Implementations/Services/ServicePath.cs index 282269e7b..ac2af3eaf 100644 --- a/Emby.Server.Implementations/Services/ServicePath.cs +++ b/Emby.Server.Implementations/Services/ServicePath.cs @@ -4,7 +4,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Text; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Extensions; namespace Emby.Server.Implementations.Services @@ -132,13 +132,13 @@ namespace Emby.Server.Implementations.Services } } - var components = componentsList.ToArray(componentsList.Count); + var components = componentsList.ToArray(); this.TotalComponentsCount = components.Length; this.literalsToMatch = new string[this.TotalComponentsCount]; this.variablesNames = new string[this.TotalComponentsCount]; this.isWildcard = new bool[this.TotalComponentsCount]; - this.componentsWithSeparators = hasSeparators.ToArray(hasSeparators.Count); + this.componentsWithSeparators = hasSeparators.ToArray(); this.PathComponentsCount = this.componentsWithSeparators.Length; string firstLiteralMatch = null; @@ -297,7 +297,7 @@ namespace Emby.Server.Implementations.Services if (mi != null && mi.IsStatic) continue; pis.Add(pi); } - return pis.ToArray(pis.Count); + return pis.ToArray(); } /// @@ -309,10 +309,10 @@ namespace Emby.Server.Implementations.Services private readonly Dictionary propertyNamesMap = new Dictionary(); - public int MatchScore(string httpMethod, string[] withPathInfoParts, ILogger logger) + public int MatchScore(string httpMethod, string[] withPathInfoParts) { int wildcardMatchCount; - var isMatch = IsMatch(httpMethod, withPathInfoParts, logger, out wildcardMatchCount); + var isMatch = IsMatch(httpMethod, withPathInfoParts, out wildcardMatchCount); if (!isMatch) { return -1; @@ -348,31 +348,27 @@ namespace Emby.Server.Implementations.Services /// For performance withPathInfoParts should already be a lower case string /// to minimize redundant matching operations. /// - public bool IsMatch(string httpMethod, string[] withPathInfoParts, ILogger logger, out int wildcardMatchCount) + public bool IsMatch(string httpMethod, string[] withPathInfoParts, out int wildcardMatchCount) { wildcardMatchCount = 0; if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath) { - //logger.Info("withPathInfoParts mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); - return false; + return false; } if (!Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase)) { - //logger.Info("allowsAllVerbs mismatch for {0} for {1} allowedverbs {2}", httpMethod, string.Join("/", withPathInfoParts), this.allowedVerbs); return false; } if (!ExplodeComponents(ref withPathInfoParts)) { - //logger.Info("ExplodeComponents mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath) { - //logger.Info("TotalComponentsCount mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } @@ -393,7 +389,6 @@ namespace Emby.Server.Implementations.Services // Ensure there are still enough parts left to match the remainder if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1)) { - //logger.Info("withPathInfoParts length mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } } @@ -416,7 +411,6 @@ namespace Emby.Server.Implementations.Services if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch)) { - //logger.Info("withPathInfoParts2 length mismatch for {0} for {1}. not equals: {2} != {3}.", httpMethod, string.Join("/", withPathInfoParts), withPathInfoParts[pathIx], literalToMatch); return false; } pathIx++; @@ -463,7 +457,7 @@ namespace Emby.Server.Implementations.Services } } - withPathInfoParts = totalComponents.ToArray(totalComponents.Count); + withPathInfoParts = totalComponents.ToArray(); return true; } @@ -574,4 +568,4 @@ namespace Emby.Server.Implementations.Services } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index df7f231c7..2b2b3c677 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -15,7 +15,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; using MediaBrowser.Model.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Session; using MediaBrowser.Model.Users; @@ -248,7 +248,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error updating user", ex); + _logger.LogError("Error updating user", ex); } } } @@ -528,7 +528,7 @@ namespace Emby.Server.Implementations.Session foreach (var session in idle) { - _logger.Debug("Session {0} has gone idle while playing", session.Id); + _logger.LogDebug("Session {0} has gone idle while playing", session.Id); try { @@ -543,7 +543,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.Debug("Error calling OnPlaybackStopped", ex); + _logger.LogDebug("Error calling OnPlaybackStopped", ex); } } @@ -847,7 +847,7 @@ namespace Emby.Server.Implementations.Session { var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.InvariantCulture) : "unknown"; - _logger.Info("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms", + _logger.LogInformation("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms", session.Client, session.ApplicationVersion, info.Item.Name, @@ -882,7 +882,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error closing live stream", ex); + _logger.LogError("Error closing live stream", ex); } } @@ -1042,7 +1042,7 @@ namespace Emby.Server.Implementations.Session command.PlayCommand = PlayCommand.PlayNow; } - command.ItemIds = items.Select(i => i.Id).ToArray(items.Count); + command.ItemIds = items.Select(i => i.Id).ToArray(); if (user != null) { @@ -1070,7 +1070,7 @@ namespace Emby.Server.Implementations.Session if (episodes.Count > 0) { - command.ItemIds = episodes.Select(i => i.Id).ToArray(episodes.Count); + command.ItemIds = episodes.Select(i => i.Id).ToArray(); } } } @@ -1095,7 +1095,7 @@ namespace Emby.Server.Implementations.Session if (item == null) { - _logger.Error("A non-existant item Id {0} was passed into TranslateItemForPlayback", id); + _logger.LogError("A non-existant item Id {0} was passed into TranslateItemForPlayback", id); return new List(); } @@ -1151,7 +1151,7 @@ namespace Emby.Server.Implementations.Session if (item == null) { - _logger.Error("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id); + _logger.LogError("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id); return new List(); } @@ -1222,7 +1222,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error in SendRestartRequiredNotification.", ex); + _logger.LogError("Error in SendRestartRequiredNotification.", ex); } }, cancellationToken)).ToArray(); @@ -1249,7 +1249,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error in SendServerShutdownNotification.", ex); + _logger.LogError("Error in SendServerShutdownNotification.", ex); } }, cancellationToken)).ToArray(); @@ -1266,7 +1266,7 @@ namespace Emby.Server.Implementations.Session { CheckDisposed(); - _logger.Debug("Beginning SendServerRestartNotification"); + _logger.LogDebug("Beginning SendServerRestartNotification"); var sessions = Sessions.ToList(); @@ -1278,7 +1278,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error in SendServerRestartNotification.", ex); + _logger.LogError("Error in SendServerRestartNotification.", ex); } }, cancellationToken)).ToArray(); @@ -1316,7 +1316,7 @@ namespace Emby.Server.Implementations.Session UserName = user.Name }); - session.AdditionalUsers = list.ToArray(list.Count); + session.AdditionalUsers = list.ToArray(); } } @@ -1345,7 +1345,7 @@ namespace Emby.Server.Implementations.Session var list = session.AdditionalUsers.ToList(); list.Remove(user); - session.AdditionalUsers = list.ToArray(list.Count); + session.AdditionalUsers = list.ToArray(); } } @@ -1462,7 +1462,7 @@ namespace Emby.Server.Implementations.Session if (existing != null) { - _logger.Info("Reissuing access token: " + existing.AccessToken); + _logger.LogInformation("Reissuing access token: " + existing.AccessToken); return existing.AccessToken; } @@ -1481,7 +1481,7 @@ namespace Emby.Server.Implementations.Session UserName = user.Name }; - _logger.Info("Creating new access token for user {0}", user.Id); + _logger.LogInformation("Creating new access token for user {0}", user.Id); _authRepo.Create(newToken); return newToken.AccessToken; @@ -1513,7 +1513,7 @@ namespace Emby.Server.Implementations.Session { CheckDisposed(); - _logger.Info("Logging out access token {0}", existing.AccessToken); + _logger.LogInformation("Logging out access token {0}", existing.AccessToken); _authRepo.Delete(existing); @@ -1529,7 +1529,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error reporting session ended", ex); + _logger.LogError("Error reporting session ended", ex); } } } @@ -1599,7 +1599,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error saving device capabilities", ex); + _logger.LogError("Error saving device capabilities", ex); } } } @@ -1669,7 +1669,7 @@ namespace Emby.Server.Implementations.Session fields.Remove(ItemFields.Tags); fields.Remove(ItemFields.ExtraIds); - dtoOptions.Fields = fields.ToArray(fields.Count); + dtoOptions.Fields = fields.ToArray(); _itemInfoDtoOptions = dtoOptions; } @@ -1692,7 +1692,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error getting {0} image info", ex, type); + _logger.LogError("Error getting {0} image info", ex, type); return null; } } @@ -1818,7 +1818,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError("Error sending message", ex); } }, cancellationToken)).ToArray(); @@ -1840,7 +1840,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError("Error sending message", ex); } }, cancellationToken)).ToArray(); @@ -1862,7 +1862,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError("Error sending message", ex); } }, cancellationToken)).ToArray(); @@ -1886,7 +1886,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError("Error sending message", ex); } }, cancellationToken)).ToArray(); diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs index 9ab4753fb..3bb022b32 100644 --- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Session; using System; @@ -40,14 +40,14 @@ namespace Emby.Server.Implementations.Session /// Initializes a new instance of the class. /// /// The session manager. - /// The log manager. + /// The logger factory. /// The json. /// The HTTP server. /// The server manager. - public SessionWebSocketListener(ISessionManager sessionManager, ILogManager logManager, IJsonSerializer json, IHttpServer httpServer) + public SessionWebSocketListener(ISessionManager sessionManager, ILoggerFactory loggerFactory, IJsonSerializer json, IHttpServer httpServer) { _sessionManager = sessionManager; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _json = json; _httpServer = httpServer; httpServer.WebSocketConnected += _serverManager_WebSocketConnected; @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Session } else { - _logger.Warn("Unable to determine session based on url: {0}", e.Argument.Url); + _logger.LogWarning("Unable to determine session based on url: {0}", e.Argument.Url); } } diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs index ddac9660f..bdae5cf8f 100644 --- a/Emby.Server.Implementations/Session/WebSocketController.cs +++ b/Emby.Server.Implementations/Session/WebSocketController.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Session; using MediaBrowser.Model.System; diff --git a/Emby.Server.Implementations/SystemEvents.cs b/Emby.Server.Implementations/SystemEvents.cs index c1e6dc1da..f39d63002 100644 --- a/Emby.Server.Implementations/SystemEvents.cs +++ b/Emby.Server.Implementations/SystemEvents.cs @@ -1,6 +1,5 @@ using System; -using MediaBrowser.Common.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; namespace Emby.Server.Implementations diff --git a/Emby.Server.Implementations/TextEncoding/TextEncoding.cs b/Emby.Server.Implementations/TextEncoding/TextEncoding.cs index ea87a9539..f30c181a0 100644 --- a/Emby.Server.Implementations/TextEncoding/TextEncoding.cs +++ b/Emby.Server.Implementations/TextEncoding/TextEncoding.cs @@ -1,7 +1,7 @@ using System; using System.Text; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Text; using NLangDetect.Core; @@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.TextEncoding if (!string.IsNullOrWhiteSpace(language)) { - _logger.Debug("Text language detected as {0}", language); + _logger.LogDebug("Text language detected as {0}", language); } } @@ -165,7 +165,7 @@ namespace Emby.Server.Implementations.TextEncoding throw new ArgumentNullException("charset"); } - _logger.Debug("Getting encoding object for character set: {0}", charset); + _logger.LogDebug("Getting encoding object for character set: {0}", charset); try { @@ -174,7 +174,7 @@ namespace Emby.Server.Implementations.TextEncoding catch (ArgumentException) { charset = charset.Replace("-", string.Empty); - _logger.Debug("Getting encoding object for character set: {0}", charset); + _logger.LogDebug("Getting encoding object for character set: {0}", charset); return Encoding.GetEncoding(charset); } diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index f195ca710..8cacc1124 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller; using MediaBrowser.Model.ApiClient; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -79,7 +79,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error in OnMessageReceived", ex); + _logger.LogError(ex, "Error in OnMessageReceived"); } } } @@ -127,7 +127,7 @@ namespace Emby.Server.Implementations.Udp } else { - _logger.Warn("Unable to respond to udp request because the local ip address could not be determined."); + _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined."); } } @@ -171,7 +171,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error receiving udp message", ex); + _logger.LogError(ex, "Error receiving udp message"); } } @@ -193,7 +193,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error receiving udp message", ex); + _logger.LogError(ex, "Error receiving udp message"); } BeginReceive(); @@ -224,7 +224,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error handling UDP message", ex); + _logger.LogError(ex, "Error handling UDP message"); } } @@ -274,7 +274,7 @@ namespace Emby.Server.Implementations.Udp { await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false); - _logger.Info("Udp message sent to {0}", remoteEndPoint); + _logger.LogInformation("Udp message sent to {remoteEndPoint}", remoteEndPoint); } catch (OperationCanceledException) { @@ -282,7 +282,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error sending message to {0}", ex, remoteEndPoint); + _logger.LogError(ex, "Error sending message to {remoteEndPoint}", remoteEndPoint); } } } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index a23166647..b4d18b69c 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -16,7 +16,7 @@ using MediaBrowser.Common.Updates; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Events; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Updates; using MediaBrowser.Controller.Configuration; @@ -76,7 +76,7 @@ namespace Emby.Server.Implementations.Updates /// The new version. private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion) { - _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.versionStr ?? string.Empty, newVersion.classification); + _logger.LogInformation("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.versionStr ?? string.Empty, newVersion.classification); EventHelper.FireEventIfNotNull(PluginUpdated, this, new GenericEventArgs> { Argument = new Tuple(plugin, newVersion) }, _logger); @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.Updates /// The package. private void OnPluginInstalled(PackageVersionInfo package) { - _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification); + _logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification); EventHelper.FireEventIfNotNull(PluginInstalled, this, new GenericEventArgs { Argument = package }, _logger); @@ -491,7 +491,7 @@ namespace Emby.Server.Implementations.Updates CurrentInstallations.Remove(tuple); } - _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr); + _logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr); EventHelper.FireEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger); @@ -499,7 +499,7 @@ namespace Emby.Server.Implementations.Updates } catch (Exception ex) { - _logger.ErrorException("Package installation failed", ex); + _logger.LogError(ex, "Package installation failed"); lock (CurrentInstallations) { @@ -610,9 +610,9 @@ namespace Emby.Server.Implementations.Updates _fileSystem.WriteAllText(target + ".ver", package.versionStr); } } - catch (IOException e) + catch (IOException ex) { - _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target); + _logger.LogError(ex, "Error attempting to move file from {TempFile} to {TargetFile}", tempFile, target); throw; } @@ -620,10 +620,10 @@ namespace Emby.Server.Implementations.Updates { _fileSystem.DeleteFile(tempFile); } - catch (IOException e) + catch (IOException ex) { // Don't fail because of this - _logger.ErrorException("Error deleting temp file {0]", e, tempFile); + _logger.LogError(ex, "Error deleting temp file {TempFile}", tempFile); } } @@ -640,7 +640,7 @@ namespace Emby.Server.Implementations.Updates _applicationHost.RemovePlugin(plugin); var path = plugin.AssemblyFilePath; - _logger.Info("Deleting plugin file {0}", path); + _logger.LogInformation("Deleting plugin file {0}", path); // Make this case-insensitive to account for possible incorrect assembly naming var file = _fileSystem.GetFilePaths(_fileSystem.GetDirectoryName(path)) diff --git a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs index 32535b69e..d96c391fb 100644 --- a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs +++ b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs @@ -87,7 +87,7 @@ namespace Emby.XmlTv.Classes if (string.IsNullOrEmpty(id)) { - //Logger.Error("No id found for channel row"); + // LogError("No id found for channel row"); // Log.Error(" channel#{0} doesnt contain an id", iChannel); return null; } @@ -130,7 +130,7 @@ namespace Emby.XmlTv.Classes if (string.IsNullOrEmpty(result.DisplayName)) { - //Logger.Error("No display-name found for channel {0}", id); + // LogError("No display-name found for channel {0}", id); return null; } @@ -302,7 +302,7 @@ namespace Emby.XmlTv.Classes var results = new Dictionary(); //Loop through and parse out all elements and then lang= attributes - //Logger.Info("Loading file {0}", _fileName); + //logger.LogInformation("Loading file {0}", _fileName); using (var reader = CreateXmlTextReader(_fileName)) { while (reader.Read()) @@ -1062,7 +1062,7 @@ namespace Emby.XmlTv.Classes } else { - //Logger.Warn("Unable to parse the date {0} from standardised form {1}", dateValue, standardDate); + //Logger.LogWarning("Unable to parse the date {0} from standardised form {1}", dateValue, standardDate); } } @@ -1091,4 +1091,4 @@ namespace Emby.XmlTv.Classes return String.Format("{0} {1}", dateComponent, dateOffset); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index 5aa803b9b..ed0a0c81a 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Threading; using System.Collections.Generic; using System.Threading; @@ -147,7 +147,7 @@ namespace MediaBrowser.Api } catch (Exception ex) { - Logger.ErrorException("Error deleting encoded media cache", ex); + Logger.LogError(ex, "Error deleting encoded media cache"); } } @@ -378,7 +378,7 @@ namespace MediaBrowser.Api public void OnTranscodeEndRequest(TranscodingJob job) { job.ActiveRequestCount--; - //Logger.Debug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount); + //Logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount); if (job.ActiveRequestCount <= 0) { PingTimer(job, false); @@ -391,7 +391,7 @@ namespace MediaBrowser.Api throw new ArgumentNullException("playSessionId"); } - //Logger.Debug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused); + //Logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused); List jobs; @@ -406,7 +406,7 @@ namespace MediaBrowser.Api { if (isUserPaused.HasValue) { - //Logger.Debug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id); + //Logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id); job.IsUserPaused = isUserPaused.Value; } PingTimer(job, true); @@ -461,7 +461,7 @@ namespace MediaBrowser.Api } } - Logger.Info("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId); + Logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId); KillTranscodingJob(job, true, path => true); } @@ -525,7 +525,7 @@ namespace MediaBrowser.Api { job.DisposeKillTimer(); - Logger.Debug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId); + Logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId); lock (_activeTranscodingJobs) { @@ -557,7 +557,7 @@ namespace MediaBrowser.Api { try { - Logger.Info("Stopping ffmpeg process with q command for {0}", job.Path); + Logger.LogInformation("Stopping ffmpeg process with q command for {path}", job.Path); //process.Kill(); process.StandardInput.WriteLine("q"); @@ -565,13 +565,13 @@ namespace MediaBrowser.Api // Need to wait because killing is asynchronous if (!process.WaitForExit(5000)) { - Logger.Info("Killing ffmpeg process for {0}", job.Path); + Logger.LogInformation("Killing ffmpeg process for {path}", job.Path); process.Kill(); } } catch (Exception ex) { - Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path); + Logger.LogError(ex, "Error killing transcoding job for {path}", job.Path); } } } @@ -589,7 +589,7 @@ namespace MediaBrowser.Api } catch (Exception ex) { - Logger.ErrorException("Error closing live stream for {0}", ex, job.Path); + Logger.LogError(ex, "Error closing live stream for {path}", job.Path); } } } @@ -601,7 +601,7 @@ namespace MediaBrowser.Api return; } - Logger.Info("Deleting partial stream file(s) {0}", path); + Logger.LogInformation("Deleting partial stream file(s) {0}", path); await Task.Delay(delayMs).ConfigureAwait(false); @@ -620,15 +620,15 @@ namespace MediaBrowser.Api { } - catch (IOException) + catch (IOException ex) { - //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); DeletePartialStreamFiles(path, jobType, retryCount + 1, 500); } - catch + catch (Exception ex) { - //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); } } @@ -660,7 +660,7 @@ namespace MediaBrowser.Api { try { - //Logger.Debug("Deleting HLS file {0}", file); + //Logger.LogDebug("Deleting HLS file {0}", file); _fileSystem.DeleteFile(file); } catch (FileNotFoundException) @@ -670,7 +670,7 @@ namespace MediaBrowser.Api catch (IOException ex) { e = ex; - //Logger.ErrorException("Error deleting HLS file {0}", ex, file); + Logger.LogError(ex, "Error deleting HLS file {path}", file); } } @@ -802,12 +802,12 @@ namespace MediaBrowser.Api { if (KillTimer == null) { - //Logger.Debug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); + //Logger.LogDebug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); KillTimer = _timerFactory.Create(callback, this, intervalMs, Timeout.Infinite); } else { - //Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); + //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); KillTimer.Change(intervalMs, Timeout.Infinite); } } @@ -826,7 +826,7 @@ namespace MediaBrowser.Api { var intervalMs = PingTimeout; - //Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); + //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); KillTimer.Change(intervalMs, Timeout.Infinite); } } diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs index db6af0c4b..07b8185c5 100644 --- a/MediaBrowser.Api/BaseApiService.cs +++ b/MediaBrowser.Api/BaseApiService.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -143,7 +143,7 @@ namespace MediaBrowser.Api { var list = options.Fields.ToList(); list.Add(Model.Querying.ItemFields.RecursiveItemCount); - options.Fields = list.ToArray(list.Count); + options.Fields = list.ToArray(); } if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 || @@ -156,7 +156,7 @@ namespace MediaBrowser.Api { var list = options.Fields.ToList(); list.Add(Model.Querying.ItemFields.ChildCount); - options.Fields = list.ToArray(list.Count); + options.Fields = list.ToArray(); } } diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index c3b2e82e7..17c6d5dc5 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -21,6 +21,8 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.IO; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; + namespace MediaBrowser.Api.Images { /// @@ -360,7 +362,7 @@ namespace MediaBrowser.Api.Images } catch (Exception ex) { - Logger.ErrorException("Error getting image information for {0}", ex, info.Path); + Logger.LogError(ex, "Error getting image information for {path}", info.Path); return null; } @@ -673,7 +675,7 @@ namespace MediaBrowser.Api.Images private ImageFormat[] GetClientSupportedFormats() { - //Logger.Debug("Request types: {0}", string.Join(",", Request.AcceptTypes ?? Array.Empty())); + //logger.LogDebug("Request types: {0}", string.Join(",", Request.AcceptTypes ?? Array.Empty())); var supportedFormats = (Request.AcceptTypes ?? Array.Empty()).Select(i => i.Split(';')[0]).ToArray(); var acceptParam = Request.QueryString["accept"]; diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs index 39a790486..331fb711d 100644 --- a/MediaBrowser.Api/ItemLookupService.cs +++ b/MediaBrowser.Api/ItemLookupService.cs @@ -17,6 +17,7 @@ using System.Threading.Tasks; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api { @@ -232,14 +233,14 @@ namespace MediaBrowser.Api // item.SetProviderId(key.Key, value); // } //} - Logger.Info("Setting provider id's to item {0}-{1}: {2}", item.Id, item.Name, _json.SerializeToString(request.ProviderIds)); + Logger.LogInformation("Setting provider id's to item {0}-{1}: {2}", item.Id, item.Name, _json.SerializeToString(request.ProviderIds)); // Since the refresh process won't erase provider Ids, we need to set this explicitly now. item.ProviderIds = request.ProviderIds; //item.ProductionYear = request.ProductionYear; //item.Name = request.Name; - return _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(_fileSystem) + return _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)) { MetadataRefreshMode = MetadataRefreshMode.FullRefresh, ImageRefreshMode = MetadataRefreshMode.FullRefresh, diff --git a/MediaBrowser.Api/ItemRefreshService.cs b/MediaBrowser.Api/ItemRefreshService.cs index ab083c207..ba1c809fe 100644 --- a/MediaBrowser.Api/ItemRefreshService.cs +++ b/MediaBrowser.Api/ItemRefreshService.cs @@ -6,7 +6,7 @@ using System.Threading; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; namespace MediaBrowser.Api diff --git a/MediaBrowser.Api/ItemUpdateService.cs b/MediaBrowser.Api/ItemUpdateService.cs index 22eb7ea09..d89750eae 100644 --- a/MediaBrowser.Api/ItemUpdateService.cs +++ b/MediaBrowser.Api/ItemUpdateService.cs @@ -230,7 +230,7 @@ namespace MediaBrowser.Api if (displayOrderChanged) { - _providerManager.QueueRefresh(series.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(series.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)) { MetadataRefreshMode = MetadataRefreshMode.FullRefresh, ImageRefreshMode = MetadataRefreshMode.FullRefresh, diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index cc8c1251f..ecf3eb7db 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -32,6 +32,7 @@ using MediaBrowser.Common.Progress; using MediaBrowser.Model.Extensions; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Library { @@ -1000,7 +1001,7 @@ namespace MediaBrowser.Api.Library } catch (Exception ex) { - Logger.ErrorException("Error refreshing library", ex); + Logger.LogError(ex, "Error refreshing library"); } }); } diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs index 510c5f135..ef9ce9aec 100644 --- a/MediaBrowser.Api/LiveTv/LiveTvService.cs +++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs @@ -17,7 +17,6 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Api.UserLibrary; using MediaBrowser.Model.IO; -using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Model.Services; @@ -974,7 +973,7 @@ namespace MediaBrowser.Api.LiveTv fields.Remove(ItemFields.CanDownload); fields.Remove(ItemFields.DisplayPreferencesId); fields.Remove(ItemFields.Etag); - options.Fields = fields.ToArray(fields.Count); + options.Fields = fields.ToArray(); } public object Get(GetChannel request) @@ -1265,4 +1264,4 @@ namespace MediaBrowser.Api.LiveTv return _liveTvManager.ResetTuner(request.Id, CancellationToken.None); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs b/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs index 0a6ccd4c5..07ac7f28d 100644 --- a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs +++ b/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs @@ -5,10 +5,10 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Library; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; using MediaBrowser.Controller.IO; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.LiveTv { @@ -95,7 +95,7 @@ namespace MediaBrowser.Api.LiveTv bytesRead = await _streamHelper.CopyToAsync(inputStream, outputStream, cancellationToken).ConfigureAwait(false); //var position = fs.Position; - //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); + //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); if (bytesRead == 0) { diff --git a/MediaBrowser.Api/Movies/MoviesService.cs b/MediaBrowser.Api/Movies/MoviesService.cs index 711280601..e8d9712de 100644 --- a/MediaBrowser.Api/Movies/MoviesService.cs +++ b/MediaBrowser.Api/Movies/MoviesService.cs @@ -123,7 +123,7 @@ namespace MediaBrowser.Api.Movies var itemsResult = _libraryManager.GetItemList(new InternalItemsQuery(user) { Limit = request.Limit, - IncludeItemTypes = itemTypes.ToArray(itemTypes.Count), + IncludeItemTypes = itemTypes.ToArray(), IsMovie = true, SimilarTo = item, EnableGroupByMetadataKey = true, @@ -177,12 +177,12 @@ namespace MediaBrowser.Api.Movies var likedMovies = _libraryManager.GetItemList(new InternalItemsQuery(user) { - IncludeItemTypes = itemTypes.ToArray(itemTypes.Count), + IncludeItemTypes = itemTypes.ToArray(), IsMovie = true, OrderBy = new[] { ItemSortBy.Random }.Select(i => new ValueTuple(i, SortOrder.Descending)).ToArray(), Limit = 10, IsFavoriteOrLiked = true, - ExcludeItemIds = recentlyPlayedMovies.Select(i => i.Id).ToArray(recentlyPlayedMovies.Count), + ExcludeItemIds = recentlyPlayedMovies.Select(i => i.Id).ToArray(), EnableGroupByMetadataKey = true, ParentId = parentIdGuid, Recursive = true, @@ -265,7 +265,7 @@ namespace MediaBrowser.Api.Movies // Account for duplicates by imdb id, since the database doesn't support this yet Limit = itemLimit + 2, PersonTypes = new[] { PersonType.Director }, - IncludeItemTypes = itemTypes.ToArray(itemTypes.Count), + IncludeItemTypes = itemTypes.ToArray(), IsMovie = true, EnableGroupByMetadataKey = true, DtoOptions = dtoOptions @@ -305,7 +305,7 @@ namespace MediaBrowser.Api.Movies Person = name, // Account for duplicates by imdb id, since the database doesn't support this yet Limit = itemLimit + 2, - IncludeItemTypes = itemTypes.ToArray(itemTypes.Count), + IncludeItemTypes = itemTypes.ToArray(), IsMovie = true, EnableGroupByMetadataKey = true, DtoOptions = dtoOptions @@ -343,7 +343,7 @@ namespace MediaBrowser.Api.Movies var similar = _libraryManager.GetItemList(new InternalItemsQuery(user) { Limit = itemLimit, - IncludeItemTypes = itemTypes.ToArray(itemTypes.Count), + IncludeItemTypes = itemTypes.ToArray(), IsMovie = true, SimilarTo = item, EnableGroupByMetadataKey = true, diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 9c2e0e9d8..af56f6382 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -24,6 +24,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Diagnostics; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback { @@ -248,7 +249,7 @@ namespace MediaBrowser.Api.Playback cancellationTokenSource); var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; - Logger.Info(commandLineLogMessage); + Logger.LogInformation(commandLineLogMessage); var logFilePrefix = "ffmpeg-transcode"; if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase)) @@ -277,7 +278,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - Logger.ErrorException("Error starting ffmpeg", ex); + Logger.LogError(ex, "Error starting ffmpeg"); ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state); @@ -351,16 +352,16 @@ namespace MediaBrowser.Api.Playback job.HasExited = true; } - Logger.Debug("Disposing stream resources"); + Logger.LogDebug("Disposing stream resources"); state.Dispose(); try { - Logger.Info("FFMpeg exited with code {0}", process.ExitCode); + Logger.LogInformation("FFMpeg exited with code {0}", process.ExitCode); } catch { - Logger.Error("FFMpeg exited with an error."); + Logger.LogError("FFMpeg exited with an error."); } // This causes on exited to be called twice: @@ -371,7 +372,7 @@ namespace MediaBrowser.Api.Playback //} //catch (Exception ex) //{ - // Logger.ErrorException("Error disposing ffmpeg.", ex); + // Logger.LogError(ex, "Error disposing ffmpeg."); //} } diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs index a0f4a2e71..7ef7b81e6 100644 --- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs @@ -15,6 +15,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Configuration; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback.Hls { @@ -185,7 +186,7 @@ namespace MediaBrowser.Api.Playback.Hls protected virtual async Task WaitForMinimumSegmentCount(string playlist, int segmentCount, CancellationToken cancellationToken) { - Logger.Debug("Waiting for {0} segments in {1}", segmentCount, playlist); + Logger.LogDebug("Waiting for {0} segments in {1}", segmentCount, playlist); while (!cancellationToken.IsCancellationRequested) { @@ -207,7 +208,7 @@ namespace MediaBrowser.Api.Playback.Hls count++; if (count >= segmentCount) { - Logger.Debug("Finished waiting for {0} segments in {1}", segmentCount, playlist); + Logger.LogDebug("Finished waiting for {0} segments in {1}", segmentCount, playlist); return; } } @@ -330,4 +331,4 @@ namespace MediaBrowser.Api.Playback.Hls { } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs index 0525c8cc4..5361e313c 100644 --- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs @@ -21,6 +21,7 @@ using System.Threading.Tasks; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Services; using MimeTypes = MediaBrowser.Model.Net.MimeTypes; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback.Hls { @@ -190,17 +191,17 @@ namespace MediaBrowser.Api.Playback.Hls if (currentTranscodingIndex == null) { - Logger.Debug("Starting transcoding because currentTranscodingIndex=null"); + Logger.LogDebug("Starting transcoding because currentTranscodingIndex=null"); startTranscoding = true; } else if (requestedIndex < currentTranscodingIndex.Value) { - Logger.Debug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex); + Logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex); startTranscoding = true; } else if (requestedIndex - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange) { - Logger.Debug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", requestedIndex - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, requestedIndex); + Logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", requestedIndex - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, requestedIndex); startTranscoding = true; } if (startTranscoding) @@ -245,13 +246,13 @@ namespace MediaBrowser.Api.Playback.Hls } } - //Logger.Info("waiting for {0}", segmentPath); + //Logger.LogInformation("waiting for {0}", segmentPath); //while (!File.Exists(segmentPath)) //{ // await Task.Delay(50, cancellationToken).ConfigureAwait(false); //} - Logger.Info("returning {0}", segmentPath); + Logger.LogInformation("returning {0}", segmentPath); job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false); } @@ -358,7 +359,7 @@ namespace MediaBrowser.Api.Playback.Hls return; } - Logger.Debug("Deleting partial HLS file {0}", path); + Logger.LogDebug("Deleting partial HLS file {path}", path); try { @@ -366,7 +367,7 @@ namespace MediaBrowser.Api.Playback.Hls } catch (IOException ex) { - Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); var task = Task.Delay(100); Task.WaitAll(task); @@ -374,7 +375,7 @@ namespace MediaBrowser.Api.Playback.Hls } catch (Exception ex) { - Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); } } @@ -968,4 +969,4 @@ namespace MediaBrowser.Api.Playback.Hls ).Trim(); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 2db0f8f41..6dafe134c 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -18,6 +18,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback { @@ -381,11 +382,11 @@ namespace MediaBrowser.Api.Playback if (item is Audio) { - Logger.Info("User policy for {0}. EnableAudioPlaybackTranscoding: {1}", user.Name, user.Policy.EnableAudioPlaybackTranscoding); + Logger.LogInformation("User policy for {0}. EnableAudioPlaybackTranscoding: {1}", user.Name, user.Policy.EnableAudioPlaybackTranscoding); } else { - Logger.Info("User policy for {0}. EnablePlaybackRemuxing: {1} EnableVideoPlaybackTranscoding: {2} EnableAudioPlaybackTranscoding: {3}", + Logger.LogInformation("User policy for {0}. EnablePlaybackRemuxing: {1} EnableVideoPlaybackTranscoding: {2} EnableAudioPlaybackTranscoding: {3}", user.Name, user.Policy.EnablePlaybackRemuxing, user.Policy.EnableVideoPlaybackTranscoding, @@ -525,7 +526,7 @@ namespace MediaBrowser.Api.Playback { var isInLocalNetwork = _networkManager.IsInLocalNetwork(Request.RemoteIp); - Logger.Info("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork); + Logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork); if (!isInLocalNetwork) { maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate); diff --git a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs index 44261f2d5..cc59b1049 100644 --- a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs +++ b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs @@ -17,6 +17,8 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; +using MediaBrowser.Api.LiveTv; namespace MediaBrowser.Api.Playback.Progressive { diff --git a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs index 9839a7a9a..ed2930b4d 100644 --- a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs +++ b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs @@ -1,16 +1,15 @@ -using MediaBrowser.Model.Logging; -using System; +using System; using System.IO; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; using MediaBrowser.Controller.Net; using System.Collections.Generic; - using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback.Progressive { @@ -110,7 +109,7 @@ namespace MediaBrowser.Api.Playback.Progressive } //var position = fs.Position; - //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); + //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); if (bytesRead == 0) { diff --git a/MediaBrowser.Api/Playback/StreamState.cs b/MediaBrowser.Api/Playback/StreamState.cs index db5d256c4..67fb04d0c 100644 --- a/MediaBrowser.Api/Playback/StreamState.cs +++ b/MediaBrowser.Api/Playback/StreamState.cs @@ -4,7 +4,6 @@ using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using System; @@ -14,6 +13,7 @@ using System.IO; using System.Linq; using System.Threading; using MediaBrowser.Controller.MediaEncoding; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback { @@ -162,7 +162,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error disposing log stream", ex); + _logger.LogError(ex, "Error disposing log stream"); } LogFileStream = null; @@ -179,7 +179,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error disposing TranscodingThrottler", ex); + _logger.LogError(ex, "Error disposing TranscodingThrottler"); } TranscodingThrottler = null; @@ -196,7 +196,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error closing media source", ex); + _logger.LogError(ex, "Error closing media source"); } } } diff --git a/MediaBrowser.Api/Playback/TranscodingThrottler.cs b/MediaBrowser.Api/Playback/TranscodingThrottler.cs index c42d0c3e4..5852852f6 100644 --- a/MediaBrowser.Api/Playback/TranscodingThrottler.cs +++ b/MediaBrowser.Api/Playback/TranscodingThrottler.cs @@ -1,9 +1,9 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Logging; using System; using MediaBrowser.Model.IO; using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback { @@ -60,7 +60,7 @@ namespace MediaBrowser.Api.Playback { if (!_isPaused) { - _logger.Debug("Sending pause command to ffmpeg"); + _logger.LogDebug("Sending pause command to ffmpeg"); try { @@ -69,7 +69,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error pausing transcoding", ex); + _logger.LogError(ex, "Error pausing transcoding"); } } } @@ -78,7 +78,7 @@ namespace MediaBrowser.Api.Playback { if (_isPaused) { - _logger.Debug("Sending unpause command to ffmpeg"); + _logger.LogDebug("Sending resume command to ffmpeg"); try { @@ -87,7 +87,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error unpausing transcoding", ex); + _logger.LogError(ex, "Error resuming transcoding"); } } } @@ -110,11 +110,11 @@ namespace MediaBrowser.Api.Playback if (gap < targetGap) { - //_logger.Debug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap); + _logger.LogDebug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap); return false; } - //_logger.Debug("Throttling transcoder gap {0} target gap {1}", gap, targetGap); + _logger.LogDebug("Throttling transcoder gap {0} target gap {1}", gap, targetGap); return true; } @@ -135,21 +135,21 @@ namespace MediaBrowser.Api.Playback if (gap < targetGap) { - //_logger.Debug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); + _logger.LogDebug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); return false; } - //_logger.Debug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); + _logger.LogDebug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); return true; } - catch + catch (Exception ex) { - //_logger.Error("Error getting output size"); + _logger.LogError(ex, "Error getting output size"); return false; } } - //_logger.Debug("No throttle data for " + path); + _logger.LogDebug("No throttle data for " + path); return false; } diff --git a/MediaBrowser.Api/PluginService.cs b/MediaBrowser.Api/PluginService.cs index 1ee096a2e..1f1bb3614 100644 --- a/MediaBrowser.Api/PluginService.cs +++ b/MediaBrowser.Api/PluginService.cs @@ -8,13 +8,13 @@ using MediaBrowser.Model.Entities; using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Serialization; using System; -using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Services; using MediaBrowser.Common.Plugins; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api { @@ -230,9 +230,9 @@ namespace MediaBrowser.Api .ToArray(); } } - catch + catch (Exception ex) { - //Logger.ErrorException("Error getting plugin list", ex); + Logger.LogError(ex, "Error getting plugin list"); // Play it safe here if (requireAppStoreEnabled) { diff --git a/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs b/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs index ff57b4dd1..fa5fa99d1 100644 --- a/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs +++ b/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs @@ -1,5 +1,5 @@ using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs b/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs index ca2c381cf..533e7d307 100644 --- a/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs +++ b/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Session; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Api/SimilarItemsHelper.cs b/MediaBrowser.Api/SimilarItemsHelper.cs index be9c1a4c5..db075e8f4 100644 --- a/MediaBrowser.Api/SimilarItemsHelper.cs +++ b/MediaBrowser.Api/SimilarItemsHelper.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; @@ -11,7 +11,6 @@ using System.Linq; using System.Threading.Tasks; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Services; -using MediaBrowser.Model.Extensions; namespace MediaBrowser.Api { @@ -81,7 +80,7 @@ namespace MediaBrowser.Api var query = new InternalItemsQuery(user) { - IncludeItemTypes = includeTypes.Select(i => i.Name).ToArray(includeTypes.Length), + IncludeItemTypes = includeTypes.Select(i => i.Name).ToArray(), Recursive = true, DtoOptions = dtoOptions }; diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index c8b0a32e9..0e5b0a964 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -17,6 +17,7 @@ using System.Threading.Tasks; using MediaBrowser.Model.IO; using MediaBrowser.Model.Services; using MimeTypes = MediaBrowser.Model.Net.MimeTypes; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Subtitles { @@ -273,11 +274,11 @@ namespace MediaBrowser.Api.Subtitles await _subtitleManager.DownloadSubtitles(video, request.SubtitleId, CancellationToken.None) .ConfigureAwait(false); - _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.High); + _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)), RefreshPriority.High); } catch (Exception ex) { - Logger.ErrorException("Error downloading subtitles", ex); + Logger.LogError(ex, "Error downloading subtitles"); } }); diff --git a/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs b/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs index 6991244c6..b61ff8d93 100644 --- a/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs +++ b/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs @@ -1,6 +1,6 @@ using MediaBrowser.Model.Activity; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Threading.Tasks; using MediaBrowser.Controller.Net; diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs index fe8b446a1..eee27ac8e 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs @@ -206,7 +206,7 @@ namespace MediaBrowser.Api.UserLibrary return new QueryResult { - Items = dtos.ToArray(result.Items.Length), + Items = dtos.ToArray(), TotalRecordCount = result.TotalRecordCount }; } diff --git a/MediaBrowser.Api/UserLibrary/PlaystateService.cs b/MediaBrowser.Api/UserLibrary/PlaystateService.cs index 2c514a109..9b269542a 100644 --- a/MediaBrowser.Api/UserLibrary/PlaystateService.cs +++ b/MediaBrowser.Api/UserLibrary/PlaystateService.cs @@ -6,9 +6,9 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Session; using System; using System.Globalization; -using System.Linq; using System.Threading.Tasks; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.UserLibrary { @@ -381,7 +381,7 @@ namespace MediaBrowser.Api.UserLibrary public void Post(ReportPlaybackStopped request) { - Logger.Debug("ReportPlaybackStopped PlaySessionId: {0}", request.PlaySessionId ?? string.Empty); + Logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", request.PlaySessionId ?? string.Empty); if (!string.IsNullOrWhiteSpace(request.PlaySessionId)) { diff --git a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs index 30df0ad23..d188d7f7e 100644 --- a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs +++ b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs @@ -404,7 +404,7 @@ namespace MediaBrowser.Api.UserLibrary if (!hasMetdata) { - var options = new MetadataRefreshOptions(_fileSystem) + var options = new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)) { MetadataRefreshMode = MetadataRefreshMode.FullRefresh, ImageRefreshMode = MetadataRefreshMode.FullRefresh, diff --git a/MediaBrowser.Api/UserLibrary/UserViewsService.cs b/MediaBrowser.Api/UserLibrary/UserViewsService.cs index 5e9270e0b..a65cc18eb 100644 --- a/MediaBrowser.Api/UserLibrary/UserViewsService.cs +++ b/MediaBrowser.Api/UserLibrary/UserViewsService.cs @@ -93,7 +93,7 @@ namespace MediaBrowser.Api.UserLibrary fields.Add(ItemFields.PrimaryImageAspectRatio); fields.Add(ItemFields.DisplayPreferencesId); fields.Remove(ItemFields.BasicSyncInfo); - dtoOptions.Fields = fields.ToArray(fields.Count); + dtoOptions.Fields = fields.ToArray(); var user = _userManager.GetUserById(request.UserId); diff --git a/MediaBrowser.Common/Events/EventHelper.cs b/MediaBrowser.Common/Events/EventHelper.cs index 2bb52f0ae..04a2270e3 100644 --- a/MediaBrowser.Common/Events/EventHelper.cs +++ b/MediaBrowser.Common/Events/EventHelper.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; @@ -28,7 +28,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.ErrorException("Error in event handler", ex); + logger.LogError(ex, "Error in event handler"); } }); } @@ -54,7 +54,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.ErrorException("Error in event handler", ex); + logger.LogError(ex, "Error in event handler"); } }); } @@ -77,7 +77,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.ErrorException("Error in event handler", ex); + logger.LogError(ex, "Error in event handler"); } } } @@ -100,7 +100,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.ErrorException("Error in event handler", ex); + logger.LogError(ex, "Error in event handler"); } } } diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index 82dece84b..2774dc944 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Users; @@ -9,9 +8,8 @@ using System.Linq; using MediaBrowser.Model.Serialization; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities.Audio { @@ -245,7 +243,7 @@ namespace MediaBrowser.Controller.Entities.Audio var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } } diff --git a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs index d60ce83ad..ec68eaf8b 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using MediaBrowser.Model.Serialization; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities.Audio { @@ -119,7 +118,7 @@ namespace MediaBrowser.Controller.Entities.Audio var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 053ee1b96..e80fe3387 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1,41 +1,32 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Library; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.Users; using System; using System.Collections.Generic; using System.Globalization; -using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; - -using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Controller.IO; -using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Querying; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.MediaInfo; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -798,7 +789,7 @@ namespace MediaBrowser.Controller.Entities builder.Append(chunkBuilder); } - //Logger.Debug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString()); + //logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString()); return builder.ToString().RemoveDiacritics(); } @@ -1295,7 +1286,7 @@ namespace MediaBrowser.Controller.Entities } } - return string.Join("/", terms.ToArray(terms.Count)); + return string.Join("/", terms.ToArray()); } /// @@ -1414,7 +1405,7 @@ namespace MediaBrowser.Controller.Entities } catch (Exception ex) { - Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name); + Logger.LogError(ex, "Error refreshing owned items for {path}", Path ?? Name); } } @@ -1536,7 +1527,7 @@ namespace MediaBrowser.Controller.Entities { var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService); - var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToArray(newThemeVideos.Length); + var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToArray(); var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds); @@ -1573,7 +1564,7 @@ namespace MediaBrowser.Controller.Entities private async Task RefreshThemeSongs(BaseItem item, MetadataRefreshOptions options, List fileSystemChildren, CancellationToken cancellationToken) { var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService); - var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToArray(newThemeSongs.Length); + var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToArray(); var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds); @@ -1802,7 +1793,7 @@ namespace MediaBrowser.Controller.Entities if (!isAllowed) { - Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating); + Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating); } return isAllowed; @@ -2058,7 +2049,7 @@ namespace MediaBrowser.Controller.Entities if (itemByPath == null) { - //Logger.Warn("Unable to find linked item at path {0}", info.Path); + //Logger.LogWarning("Unable to find linked item at path {0}", info.Path); } return itemByPath; @@ -2070,7 +2061,7 @@ namespace MediaBrowser.Controller.Entities if (item == null) { - //Logger.Warn("Unable to find linked item at path {0}", info.Path); + //Logger.LogWarning("Unable to find linked item at path {0}", info.Path); } return item; @@ -2110,9 +2101,8 @@ namespace MediaBrowser.Controller.Entities } else { - var list = current.ToArray(current.Length + 1); - list[list.Length - 1] = name; - Studios = list; + var list = + Studios = current.Concat(new [] { name }).ToArray(); } } } @@ -2214,7 +2204,7 @@ namespace MediaBrowser.Controller.Entities /// Task. public virtual void ChangedExternally() { - ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem) + ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)) { }, RefreshPriority.High); @@ -2252,9 +2242,7 @@ namespace MediaBrowser.Controller.Entities else { var currentCount = ImageInfos.Length; - var newList = ImageInfos.ToArray(currentCount + 1); - newList[currentCount] = image; - ImageInfos = newList; + ImageInfos = ImageInfos.Concat(new [] { image }) .ToArray(); } } @@ -2269,10 +2257,7 @@ namespace MediaBrowser.Controller.Entities if (image == null) { - var currentCount = ImageInfos.Length; - var newList = ImageInfos.ToArray(currentCount + 1); - newList[currentCount] = GetImageInfo(file, type); - ImageInfos = newList; + ImageInfos = ImageInfos.Concat(new [] { GetImageInfo(file, type) }) .ToArray(); } else { @@ -2486,16 +2471,7 @@ namespace MediaBrowser.Controller.Entities if (newImageList.Count > 0) { - var currentCount = ImageInfos.Length; - var newList = ImageInfos.ToArray(currentCount + newImageList.Count); - - foreach (var image in newImageList) - { - newList[currentCount] = GetImageInfo(image, imageType); - currentCount++; - } - - ImageInfos = newList; + ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray(); } return imageUpdated || newImageList.Count > 0; @@ -2537,7 +2513,7 @@ namespace MediaBrowser.Controller.Entities var extensions = new List { ".nfo", ".xml", ".srt", ".vtt", ".sub", ".idx", ".txt", ".edl", ".bif", ".smi", ".ttml" }; extensions.AddRange(SupportedImageExtensions); - return FileSystem.GetFiles(FileSystem.GetDirectoryName(Path), extensions.ToArray(extensions.Count), false, false) + return FileSystem.GetFiles(FileSystem.GetDirectoryName(Path), extensions.ToArray(), false, false) .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase)) .ToList(); } @@ -2776,7 +2752,7 @@ namespace MediaBrowser.Controller.Entities { var list = GetEtagValues(user); - return string.Join("|", list.ToArray(list.Count)).GetMD5().ToString("N"); + return string.Join("|", list.ToArray()).GetMD5().ToString("N"); } protected virtual List GetEtagValues(User user) diff --git a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs index c56a370a8..8ab1788b5 100644 --- a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs +++ b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -61,5 +62,46 @@ namespace MediaBrowser.Controller.Entities item.SetImagePath(imageType, BaseItem.FileSystem.GetFileInfo(file)); } } + + /// + /// Copies all properties on object. Skips properties that do not exist. + /// + /// The source object. + /// The destination object. + public static void DeepCopy(this T source, TU dest) + where T : BaseItem + where TU : BaseItem + { + var sourceProps = typeof (T).GetProperties().Where(x => x.CanRead).ToList(); + var destProps = typeof(TU).GetProperties() + .Where(x => x.CanWrite) + .ToList(); + + foreach (var sourceProp in sourceProps) + { + if (destProps.Any(x => x.Name == sourceProp.Name)) + { + var p = destProps.First(x => x.Name == sourceProp.Name); + p.SetValue(dest, sourceProp.GetValue(source, null), null); + } + + } + + } + + /// + /// Copies all properties on newly created object. Skips properties that do not exist. + /// + /// The source object. + public static TU DeepCopy(this T source) + where T : BaseItem + where TU : BaseItem, new() + { + var dest = new TU(); + source.DeepCopy(dest); + return dest; + } + + } } diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 8240a68ff..7292b166a 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -1,13 +1,13 @@ -using MediaBrowser.Controller.IO; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.IO; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; @@ -15,6 +15,8 @@ using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; + namespace MediaBrowser.Controller.Entities { /// @@ -103,7 +105,7 @@ namespace MediaBrowser.Controller.Entities } catch (Exception ex) { - Logger.ErrorException("Error loading library options", ex); + Logger.LogError(ex, "Error loading library options"); return new LibraryOptions(); } @@ -275,7 +277,7 @@ namespace MediaBrowser.Controller.Entities var changed = !linkedChildren.SequenceEqual(LinkedChildren, new LinkedChildComparer(FileSystem)); - LinkedChildren = linkedChildren.ToArray(linkedChildren.Count); + LinkedChildren = linkedChildren.ToArray(); var folderIds = PhysicalFolderIds; var newFolderIds = physicalFolders.Select(i => i.Id).ToArray(); diff --git a/MediaBrowser.Controller/Entities/Extensions.cs b/MediaBrowser.Controller/Entities/Extensions.cs index c706cf36c..ee135a14e 100644 --- a/MediaBrowser.Controller/Entities/Extensions.cs +++ b/MediaBrowser.Controller/Entities/Extensions.cs @@ -35,10 +35,7 @@ namespace MediaBrowser.Controller.Entities } else { - var list = item.RemoteTrailers.ToArray(item.RemoteTrailers.Length + 1); - list[list.Length - 1] = mediaUrl; - - item.RemoteTrailers = list; + item.RemoteTrailers = item.RemoteTrailers.Concat(new [] { mediaUrl }).ToArray(); } } } diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 8b9aa5fc3..dbe30f9a5 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -10,7 +10,6 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; - using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities.Audio; @@ -23,6 +22,7 @@ using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Extensions; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -264,7 +264,7 @@ namespace MediaBrowser.Controller.Entities /// protected virtual List LoadChildren() { - //Logger.Debug("Loading children from {0} {1} {2}", GetType().Name, Id, Path); + //logger.LogDebug("Loading children from {0} {1} {2}", GetType().Name, Id, Path); //just load our children from the repo - the library will be validated and maintained in other processes return GetCachedChildren(); } @@ -303,7 +303,7 @@ namespace MediaBrowser.Controller.Entities var id = child.Id; if (dictionary.ContainsKey(id)) { - Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}", + Logger.LogError("Found folder containing items with duplicate id. Path: {path}, Child Name: {ChildName}", Path ?? Name, child.Path ?? child.Name); } @@ -371,6 +371,7 @@ namespace MediaBrowser.Controller.Entities } catch (Exception ex) { + Logger.LogError(ex, "Error retrieving children folder"); return; } @@ -419,13 +420,9 @@ namespace MediaBrowser.Controller.Entities foreach (var item in itemsRemoved) { - if (!item.IsFileProtocol) + if (item.IsFileProtocol) { - } - - else - { - Logger.Debug("Removed item: " + item.Path); + Logger.LogDebug("Removed item: " + item.Path); item.SetParent(null); LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }, this, false); @@ -571,14 +568,9 @@ namespace MediaBrowser.Controller.Entities await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); } - if (recursive) + if (recursive && child is Folder folder) { - var folder = child as Folder; - - if (folder != null) - { - await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken); - } + await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken); } } } @@ -782,7 +774,7 @@ namespace MediaBrowser.Controller.Entities { if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(BoxSet).Name, StringComparison.OrdinalIgnoreCase)) { - Logger.Debug("Query requires post-filtering due to BoxSet query"); + Logger.LogDebug("Query requires post-filtering due to BoxSet query"); return true; } @@ -795,7 +787,7 @@ namespace MediaBrowser.Controller.Entities { if (!(this is ICollectionFolder)) { - Logger.Debug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name); + Logger.LogDebug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name); return true; } } @@ -803,68 +795,68 @@ namespace MediaBrowser.Controller.Entities // Filter by Video3DFormat if (query.Is3D.HasValue) { - Logger.Debug("Query requires post-filtering due to Is3D"); + Logger.LogDebug("Query requires post-filtering due to Is3D"); return true; } if (query.HasOfficialRating.HasValue) { - Logger.Debug("Query requires post-filtering due to HasOfficialRating"); + Logger.LogDebug("Query requires post-filtering due to HasOfficialRating"); return true; } if (query.IsPlaceHolder.HasValue) { - Logger.Debug("Query requires post-filtering due to IsPlaceHolder"); + Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder"); return true; } if (query.HasSpecialFeature.HasValue) { - Logger.Debug("Query requires post-filtering due to HasSpecialFeature"); + Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature"); return true; } if (query.HasSubtitles.HasValue) { - Logger.Debug("Query requires post-filtering due to HasSubtitles"); + Logger.LogDebug("Query requires post-filtering due to HasSubtitles"); return true; } if (query.HasTrailer.HasValue) { - Logger.Debug("Query requires post-filtering due to HasTrailer"); + Logger.LogDebug("Query requires post-filtering due to HasTrailer"); return true; } // Filter by VideoType if (query.VideoTypes.Length > 0) { - Logger.Debug("Query requires post-filtering due to VideoTypes"); + Logger.LogDebug("Query requires post-filtering due to VideoTypes"); return true; } if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager)) { - Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems"); + Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems"); return true; } if (!string.IsNullOrEmpty(query.AdjacentTo)) { - Logger.Debug("Query requires post-filtering due to AdjacentTo"); + Logger.LogDebug("Query requires post-filtering due to AdjacentTo"); return true; } if (query.SeriesStatuses.Length > 0) { - Logger.Debug("Query requires post-filtering due to SeriesStatuses"); + Logger.LogDebug("Query requires post-filtering due to SeriesStatuses"); return true; } if (query.AiredDuringSeason.HasValue) { - Logger.Debug("Query requires post-filtering due to AiredDuringSeason"); + Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason"); return true; } @@ -872,7 +864,7 @@ namespace MediaBrowser.Controller.Entities { if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name)) { - Logger.Debug("Query requires post-filtering due to IsPlayed"); + Logger.LogDebug("Query requires post-filtering due to IsPlayed"); return true; } } @@ -914,7 +906,7 @@ namespace MediaBrowser.Controller.Entities // Try to preserve order return result.OrderBy(i => ids.IndexOf(i.Id)).ToArray(); } - return result.ToArray(result.Count); + return result.ToArray(); } return GetItemsInternal(query).Items; @@ -1575,7 +1567,7 @@ namespace MediaBrowser.Controller.Entities { try { - Logger.Debug("Found shortcut at {0}", i.FullName); + Logger.LogDebug("Found shortcut at {0}", i.FullName); var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShortcut(i.FullName)); @@ -1588,13 +1580,13 @@ namespace MediaBrowser.Controller.Entities }; } - Logger.Error("Error resolving shortcut {0}", i.FullName); + Logger.LogError("Error resolving shortcut {0}", i.FullName); return null; } catch (IOException ex) { - Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName); + Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName); return null; } }) @@ -1605,10 +1597,10 @@ namespace MediaBrowser.Controller.Entities if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem))) { - Logger.Info("Shortcut links have changed for {0}", Path); + Logger.LogInformation("Shortcut links have changed for {0}", Path); newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual)); - LinkedChildren = newShortcutLinks.ToArray(newShortcutLinks.Count); + LinkedChildren = newShortcutLinks.ToArray(); return true; } } diff --git a/MediaBrowser.Controller/Entities/GameGenre.cs b/MediaBrowser.Controller/Entities/GameGenre.cs index 63493ad4a..ba178d3c3 100644 --- a/MediaBrowser.Controller/Entities/GameGenre.cs +++ b/MediaBrowser.Controller/Entities/GameGenre.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using MediaBrowser.Model.Serialization; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -102,7 +101,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs index 94a5984df..57ffe2744 100644 --- a/MediaBrowser.Controller/Entities/Genre.cs +++ b/MediaBrowser.Controller/Entities/Genre.cs @@ -2,9 +2,8 @@ using MediaBrowser.Controller.Entities.Audio; using System; using System.Collections.Generic; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -114,7 +113,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs index 64d775094..5c35a7411 100644 --- a/MediaBrowser.Controller/Entities/Person.cs +++ b/MediaBrowser.Controller/Entities/Person.cs @@ -1,11 +1,10 @@ using MediaBrowser.Controller.Providers; using System; using System.Collections.Generic; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -137,7 +136,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/Studio.cs b/MediaBrowser.Controller/Entities/Studio.cs index 29f617539..c076cd680 100644 --- a/MediaBrowser.Controller/Entities/Studio.cs +++ b/MediaBrowser.Controller/Entities/Studio.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using MediaBrowser.Model.Serialization; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -115,7 +114,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index 201579731..3a3a902a3 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -7,6 +7,7 @@ using System.Globalization; using System.Linq; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities.TV { @@ -363,7 +364,7 @@ namespace MediaBrowser.Controller.Entities.TV } catch (Exception ex) { - Logger.ErrorException("Error in FillMissingEpisodeNumbersFromPath. Episode: {0}", ex, Path ?? Name ?? Id.ToString()); + Logger.LogError(ex, "Error in FillMissingEpisodeNumbersFromPath. Episode: {Episode}", Path ?? Name ?? Id.ToString()); } } } diff --git a/MediaBrowser.Controller/Entities/TagExtensions.cs b/MediaBrowser.Controller/Entities/TagExtensions.cs index e5d8f35d9..84e61be4f 100644 --- a/MediaBrowser.Controller/Entities/TagExtensions.cs +++ b/MediaBrowser.Controller/Entities/TagExtensions.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Linq; -using MediaBrowser.Model.Extensions; namespace MediaBrowser.Controller.Entities { @@ -24,10 +22,7 @@ namespace MediaBrowser.Controller.Entities } else { - var list = current.ToArray(current.Length + 1); - list[list.Length - 1] = name; - - item.Tags = list; + item.Tags = current.Concat(new [] { name }).ToArray(); } } } diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index 36035a2bb..b50a12d52 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.TV; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; @@ -259,10 +259,9 @@ namespace MediaBrowser.Controller.Entities { return _libraryManager.GetGenre(i); } - catch + catch (Exception ex) { - // Full exception logged at lower levels - _logger.Error("Error getting genre"); + _logger.LogError(ex, "Error getting genre"); return null; } @@ -383,10 +382,9 @@ namespace MediaBrowser.Controller.Entities { return _libraryManager.GetGenre(i); } - catch + catch (Exception ex) { - // Full exception logged at lower levels - _logger.Error("Error getting genre"); + _logger.LogError(ex, "Error getting genre"); return null; } diff --git a/MediaBrowser.Controller/Entities/Year.cs b/MediaBrowser.Controller/Entities/Year.cs index 81e030cea..8e3cd0b70 100644 --- a/MediaBrowser.Controller/Entities/Year.cs +++ b/MediaBrowser.Controller/Entities/Year.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -121,7 +122,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/IO/FileData.cs b/MediaBrowser.Controller/IO/FileData.cs index e1fabee4f..c0cf51ab2 100644 --- a/MediaBrowser.Controller/IO/FileData.cs +++ b/MediaBrowser.Controller/IO/FileData.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Model.IO; @@ -77,7 +77,7 @@ namespace MediaBrowser.Controller.IO if (string.IsNullOrEmpty(newPath)) { //invalid shortcut - could be old or target could just be unavailable - logger.Warn("Encountered invalid shortcut: " + fullName); + logger.LogWarning("Encountered invalid shortcut: " + fullName); continue; } @@ -91,7 +91,7 @@ namespace MediaBrowser.Controller.IO } catch (Exception ex) { - logger.ErrorException("Error resolving shortcut from {0}", ex, fullName); + logger.LogError(ex, "Error resolving shortcut from {path}", fullName); } } else if (flattenFolderDepth > 0 && isDirectory) diff --git a/MediaBrowser.Controller/IResourceFileManager.cs b/MediaBrowser.Controller/IResourceFileManager.cs index ae73f4b4c..64f1b9f7a 100644 --- a/MediaBrowser.Controller/IResourceFileManager.cs +++ b/MediaBrowser.Controller/IResourceFileManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; diff --git a/MediaBrowser.Controller/Library/Profiler.cs b/MediaBrowser.Controller/Library/Profiler.cs index 3957c3020..745e49920 100644 --- a/MediaBrowser.Controller/Library/Profiler.cs +++ b/MediaBrowser.Controller/Library/Profiler.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; @@ -67,7 +67,7 @@ namespace MediaBrowser.Controller.Library message = string.Format("{0} took {1} seconds.", _name, ((float)_stopwatch.ElapsedMilliseconds / 1000).ToString("#0.000")); } - _logger.Info(message); + _logger.LogInformation(message); } } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 3d2871e65..c8c2367e6 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -8,10 +8,10 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Session; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.MediaEncoding { @@ -727,7 +727,6 @@ namespace MediaBrowser.Controller.MediaEncoding return count; } - protected void DisposeIsoMount() { if (IsoMount != null) @@ -738,7 +737,7 @@ namespace MediaBrowser.Controller.MediaEncoding } catch (Exception ex) { - _logger.ErrorException("Error disposing iso mount", ex); + _logger.LogError(ex, "Error disposing iso mount"); } IsoMount = null; diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs index 5f3f79d77..8bb826bd1 100644 --- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs +++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs @@ -1,10 +1,10 @@ using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; using System; using System.Globalization; using System.IO; using System.Linq; using System.Text; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.MediaEncoding { @@ -43,7 +43,7 @@ namespace MediaBrowser.Controller.MediaEncoding } catch (Exception ex) { - _logger.ErrorException("Error reading ffmpeg log", ex); + _logger.LogError(ex, "Error reading ffmpeg log"); } } diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs index 7df96b777..31ec149bf 100644 --- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs +++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Net; +using MediaBrowser.Model.Net; using MediaBrowser.Model.Threading; using System.Collections.Generic; using System.Globalization; @@ -8,6 +7,7 @@ using System.Net.WebSockets; using System.Threading.Tasks; using System.Threading; using System; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Net { @@ -114,7 +114,7 @@ namespace MediaBrowser.Controller.Net var cancellationTokenSource = new CancellationTokenSource(); - Logger.Debug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name); + Logger.LogDebug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name); var timer = SendOnTimer ? TimerFactory.Create(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite) : @@ -229,7 +229,7 @@ namespace MediaBrowser.Controller.Net } catch (Exception ex) { - Logger.ErrorException("Error sending web socket message {0}", ex, Name); + Logger.LogError(ex, "Error sending web socket message {Name}", Name); DisposeConnection(tuple); } } @@ -257,7 +257,7 @@ namespace MediaBrowser.Controller.Net /// The connection. private void DisposeConnection(Tuple connection) { - Logger.Debug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name); + Logger.LogDebug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name); var timer = connection.Item3; diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs index 65192671e..9bb2f5bed 100644 --- a/MediaBrowser.Controller/Providers/DirectoryService.cs +++ b/MediaBrowser.Controller/Providers/DirectoryService.cs @@ -1,10 +1,7 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; -using System.Collections.Concurrent; using System.Collections.Generic; -using System.IO; using System.Linq; -using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; namespace MediaBrowser.Controller.Providers @@ -26,18 +23,13 @@ namespace MediaBrowser.Controller.Providers _fileSystem = fileSystem; } - public DirectoryService(IFileSystem fileSystem) - : this(new NullLogger(), fileSystem) - { - } - public FileSystemMetadata[] GetFileSystemEntries(string path) { FileSystemMetadata[] entries; if (!_cache.TryGetValue(path, out entries)) { - //_logger.Debug("Getting files for " + path); + //_logger.LogDebug("Getting files for " + path); entries = _fileSystem.GetFileSystemEntries(path).ToArray(); diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index 3e34075a6..2494be83a 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -4,7 +4,7 @@ using System.Linq; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; namespace MediaBrowser.Controller.Providers @@ -24,11 +24,6 @@ namespace MediaBrowser.Controller.Providers public bool ForceSave { get; set; } public bool EnableRemoteContentProbe { get; set; } - public MetadataRefreshOptions(IFileSystem fileSystem) - : this(new DirectoryService(new NullLogger(), fileSystem)) - { - } - public MetadataRefreshOptions(IDirectoryService directoryService) : base(directoryService) { diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs index 869d3fcb0..98848a440 100644 --- a/MediaBrowser.Controller/Session/SessionInfo.cs +++ b/MediaBrowser.Controller/Session/SessionInfo.cs @@ -1,11 +1,11 @@ -using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Session; +using System; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Threading; using System.Linq; -using System; namespace MediaBrowser.Controller.Session { @@ -231,7 +231,7 @@ namespace MediaBrowser.Controller.Session } var newController = factory(this); - _logger.Debug("Creating new {0}", newController.GetType().Name); + _logger.LogDebug("Creating new {0}", newController.GetType().Name); controllers.Add(newController); SessionControllers = controllers.ToArray(); @@ -337,7 +337,7 @@ namespace MediaBrowser.Controller.Session } catch (Exception ex) { - _logger.ErrorException("Error reporting playback progress", ex); + _logger.LogError(ex, "Error reporting playback progress"); } } @@ -371,7 +371,7 @@ namespace MediaBrowser.Controller.Session if (disposable != null) { - _logger.Debug("Disposing session controller {0}", disposable.GetType().Name); + _logger.LogDebug("Disposing session controller {0}", disposable.GetType().Name); try { @@ -379,7 +379,7 @@ namespace MediaBrowser.Controller.Session } catch (Exception ex) { - _logger.ErrorException("Error disposing session controller", ex); + _logger.LogError(ex, "Error disposing session controller"); } } } diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs index 05874ec2c..c22ca4d60 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs @@ -10,7 +10,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Parsers @@ -158,7 +158,7 @@ namespace MediaBrowser.LocalMetadata.Parsers } else { - Logger.Warn("Invalid Added value found: " + val); + Logger.LogWarning("Invalid Added value found: " + val); } } break; diff --git a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs index 33eb75edb..e5b4190a4 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs @@ -1,12 +1,11 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Xml; using MediaBrowser.Model.IO; using MediaBrowser.Model.Xml; -using MediaBrowser.Model.Extensions; namespace MediaBrowser.LocalMetadata.Parsers { @@ -85,7 +84,7 @@ namespace MediaBrowser.LocalMetadata.Parsers } } - item.Item.LinkedChildren = list.ToArray(list.Count); + item.Item.LinkedChildren = list.ToArray(); } public BoxSetXmlParser(ILogger logger, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory, IFileSystem fileSystem) : base(logger, providerManager, xmlReaderSettingsFactory, fileSystem) diff --git a/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs index 3225603bf..0139ce917 100644 --- a/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Threading; using System.Threading.Tasks; using System.Xml; diff --git a/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs index f9b334396..939e2d1df 100644 --- a/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Parsers diff --git a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs index 10f46e5a4..dcf88e90e 100644 --- a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -95,7 +95,7 @@ namespace MediaBrowser.LocalMetadata.Parsers } } - item.LinkedChildren = list.ToArray(list.Count); + item.LinkedChildren = list.ToArray(); } public PlaylistXmlParser(ILogger logger, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory, IFileSystem fileSystem) : base(logger, providerManager, xmlReaderSettingsFactory, fileSystem) diff --git a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs index 30576b531..2629547f8 100644 --- a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Providers; using MediaBrowser.LocalMetadata.Parsers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.IO; using System.Threading; diff --git a/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs index 006376b41..4ca7224ca 100644 --- a/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Providers; using MediaBrowser.LocalMetadata.Parsers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Providers diff --git a/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs index 3e7acc28d..0ba52f84d 100644 --- a/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.LocalMetadata.Parsers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.IO; using System.Threading; diff --git a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs index 909daf2dd..ce37adda3 100644 --- a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; using MediaBrowser.LocalMetadata.Parsers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.IO; using System.Threading; using MediaBrowser.LocalMetadata.Savers; diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index 81622f54c..9666c8266 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -20,7 +20,7 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers @@ -135,7 +135,7 @@ namespace MediaBrowser.LocalMetadata.Savers } catch (Exception ex) { - Logger.Error("Error setting hidden attribute on {0} - {1}", path, ex.Message); + Logger.LogError(ex, "Error setting hidden attribute on {path}", path); } } diff --git a/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs index 42a96588a..1995d8c38 100644 --- a/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs @@ -10,7 +10,7 @@ using System.Xml; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs index 109b21d35..da0d82490 100644 --- a/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Xml; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs index 1a8e83e72..62d4993b3 100644 --- a/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs @@ -6,7 +6,7 @@ using System.Globalization; using System.IO; using System.Xml; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs index 8409e483d..a84fcd57e 100644 --- a/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Xml; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs index 521a0b00e..0c03bcacd 100644 --- a/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.IO; using System.Xml; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs index 566e7946d..2a874eba1 100644 --- a/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Session; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using MediaBrowser.Model.Diagnostics; diff --git a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs index 3383276bc..187f350b8 100644 --- a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs @@ -7,7 +7,7 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; @@ -105,7 +105,7 @@ namespace MediaBrowser.MediaEncoding.Encoder OnTranscodeBeginning(encodingJob); var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; - Logger.Info(commandLineLogMessage); + Logger.LogInformation(commandLineLogMessage); var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt"); FileSystem.CreateDirectory(FileSystem.GetDirectoryName(logFilePath)); @@ -124,7 +124,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - Logger.ErrorException("Error starting ffmpeg", ex); + Logger.LogError(ex, "Error starting ffmpeg"); OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob); @@ -150,7 +150,7 @@ namespace MediaBrowser.MediaEncoding.Encoder private void Cancel(IProcess process, EncodingJob job) { - Logger.Info("Killing ffmpeg process for {0}", job.OutputFilePath); + Logger.LogInformation("Killing ffmpeg process for {0}", job.OutputFilePath); //process.Kill(); process.StandardInput.WriteLine("q"); @@ -167,7 +167,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { job.HasExited = true; - Logger.Debug("Disposing stream resources"); + Logger.LogDebug("Disposing stream resources"); job.Dispose(); var isSuccesful = false; @@ -175,13 +175,13 @@ namespace MediaBrowser.MediaEncoding.Encoder try { var exitCode = process.ExitCode; - Logger.Info("FFMpeg exited with code {0}", exitCode); + Logger.LogInformation("FFMpeg exited with code {0}", exitCode); isSuccesful = exitCode == 0; } - catch + catch (Exception ex) { - Logger.Error("FFMpeg exited with an error."); + Logger.LogError(ex, "FFMpeg exited with an error."); } if (isSuccesful && !job.IsCancelled) @@ -231,7 +231,7 @@ namespace MediaBrowser.MediaEncoding.Encoder //} //catch (Exception ex) //{ - // Logger.ErrorException("Error disposing ffmpeg.", ex); + // Logger.LogError("Error disposing ffmpeg.", ex); //} } diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 59f3576ec..fb131f304 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using MediaBrowser.Model.Diagnostics; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace MediaBrowser.MediaEncoding.Encoder { @@ -20,12 +20,12 @@ namespace MediaBrowser.MediaEncoding.Encoder public Tuple, List> Validate(string encoderPath) { - _logger.Info("Validating media encoder at {0}", encoderPath); + _logger.LogInformation("Validating media encoder at {0}", encoderPath); var decoders = GetDecoders(encoderPath); var encoders = GetEncoders(encoderPath); - _logger.Info("Encoder validation complete"); + _logger.LogInformation("Encoder validation complete"); return new Tuple, List>(decoders, encoders); } @@ -41,7 +41,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { if (logOutput) { - _logger.ErrorException("Error validating encoder", ex); + _logger.LogError(ex, "Error validating encoder"); } } @@ -50,7 +50,7 @@ namespace MediaBrowser.MediaEncoding.Encoder return false; } - _logger.Info("ffmpeg info: {0}", output); + _logger.LogInformation("ffmpeg info: {0}", output); if (output.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1) { @@ -78,9 +78,9 @@ namespace MediaBrowser.MediaEncoding.Encoder { output = GetProcessOutput(encoderAppPath, "-decoders"); } - catch (Exception ) + catch (Exception ex) { - //_logger.ErrorException("Error detecting available decoders", ex); + _logger.LogError(ex, "Error detecting available decoders"); } var found = new List(); @@ -107,7 +107,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1) { - _logger.Info("Decoder available: " + codec); + _logger.LogInformation("Decoder available: " + codec); found.Add(codec); } } @@ -163,7 +163,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { if (index < required.Length - 1) { - _logger.Info("Encoder available: " + codec); + _logger.LogInformation("Encoder available: " + codec); } found.Add(codec); @@ -187,7 +187,7 @@ namespace MediaBrowser.MediaEncoding.Encoder RedirectStandardOutput = true }); - _logger.Info("Running {0} {1}", path, arguments); + _logger.LogInformation("Running {path} {arguments}", path, arguments); using (process) { @@ -199,16 +199,16 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch { - _logger.Info("Killing process {0} {1}", path, arguments); + _logger.LogInformation("Killing process {path} {arguments}", path, arguments); // Hate having to do this try { process.Kill(); } - catch (Exception ex1) + catch (Exception ex) { - _logger.ErrorException("Error killing process", ex1); + _logger.LogError(ex, "Error killing process"); } throw; diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs index 294181fcc..e97898ac5 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs @@ -5,7 +5,6 @@ using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using System; @@ -14,6 +13,7 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace MediaBrowser.MediaEncoding.Encoder { @@ -81,7 +81,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.ErrorException("Error disposing log stream", ex); + _logger.LogError(ex, "Error disposing log stream"); } LogFileStream = null; @@ -98,7 +98,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.ErrorException("Error closing media source", ex); + _logger.LogError(ex, "Error closing media source"); } } } diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs index 8d8d05a16..4e6ee89e1 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs @@ -5,7 +5,7 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; diff --git a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs index e21292cbd..d2cf7f395 100644 --- a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs +++ b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs @@ -10,7 +10,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Common.Progress; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; namespace MediaBrowser.MediaEncoding.Encoder @@ -72,12 +72,12 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (HttpException ex) { // Don't let the server crash because of this - _logger.ErrorException("Error downloading ffmpeg font files", ex); + _logger.LogError(ex, "Error downloading ffmpeg font files"); } catch (Exception ex) { // Don't let the server crash because of this - _logger.ErrorException("Error writing ffmpeg font files", ex); + _logger.LogError(ex, "Error writing ffmpeg font files"); } } @@ -103,7 +103,7 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (IOException ex) { // Log this, but don't let it fail the operation - _logger.ErrorException("Error copying file", ex); + _logger.LogError(ex, "Error copying file"); } } @@ -127,7 +127,7 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (Exception ex) { // The core can function without the font file, so handle this - _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url); + _logger.LogError(ex, "Failed to download ffmpeg font file from {url}", url); } } @@ -145,12 +145,12 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (IOException ex) { // Log this, but don't let it fail the operation - _logger.ErrorException("Error deleting temp file {0}", ex, tempFile); + _logger.LogError(ex, "Error deleting temp file {path}", tempFile); } } private void Extract7zArchive(string archivePath, string targetPath) { - _logger.Info("Extracting {0} to {1}", archivePath, targetPath); + _logger.LogInformation("Extracting {ArchivePath} to {TargetPath}", archivePath, targetPath); _zipClient.ExtractAllFrom7z(archivePath, targetPath, true); } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 64372c072..a661d7691 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -9,7 +9,6 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -25,6 +24,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; namespace MediaBrowser.MediaEncoding.Encoder { @@ -102,8 +102,6 @@ namespace MediaBrowser.MediaEncoding.Encoder _originalFFMpegPath = ffMpegPath; _hasExternalEncoder = hasExternalEncoder; - - SetEnvironmentVariable(); } private readonly object _logLock = new object(); @@ -117,7 +115,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.ErrorException("Error setting FFREPORT environment variable", ex); + _logger.LogError(ex, "Error setting FFREPORT environment variable"); } } } @@ -132,31 +130,11 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - //_logger.ErrorException("Error setting FFREPORT environment variable", ex); + _logger.LogError(ex, "Error setting FFREPORT environment variable"); } } } - private void SetEnvironmentVariable() - { - try - { - //_environmentInfo.SetProcessEnvironmentVariable("FFREPORT", "file=program-YYYYMMDD-HHMMSS.txt:level=32"); - } - catch (Exception ex) - { - _logger.ErrorException("Error setting FFREPORT environment variable", ex); - } - try - { - //_environmentInfo.SetUserEnvironmentVariable("FFREPORT", "file=program-YYYYMMDD-HHMMSS.txt:level=32"); - } - catch (Exception ex) - { - _logger.ErrorException("Error setting FFREPORT environment variable", ex); - } - } - public string EncoderLocationType { get @@ -252,7 +230,7 @@ namespace MediaBrowser.MediaEncoding.Encoder return; } - _logger.Info("Attempting to update encoder path to {0}. pathType: {1}", path ?? string.Empty, pathType ?? string.Empty); + _logger.LogInformation("Attempting to update encoder path to {0}. pathType: {1}", path ?? string.Empty, pathType ?? string.Empty); Tuple newPaths; @@ -414,8 +392,8 @@ namespace MediaBrowser.MediaEncoding.Encoder private void LogPaths() { - _logger.Info("FFMpeg: {0}", FFMpegPath ?? "not found"); - _logger.Info("FFProbe: {0}", FFProbePath ?? "not found"); + _logger.LogInformation("FFMpeg: {0}", FFMpegPath ?? "not found"); + _logger.LogInformation("FFProbe: {0}", FFProbePath ?? "not found"); } private EncodingOptions GetEncodingOptions() @@ -557,11 +535,11 @@ namespace MediaBrowser.MediaEncoding.Encoder if (forceEnableLogging) { - _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); } else { - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); } using (var processWrapper = new ProcessWrapper(process, this, _logger)) @@ -649,9 +627,9 @@ namespace MediaBrowser.MediaEncoding.Encoder { throw; } - catch + catch (Exception ex) { - _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument); + _logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {arguments}", inputArgument); } } @@ -755,7 +733,7 @@ namespace MediaBrowser.MediaEncoding.Encoder ErrorDialog = false }); - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); using (var processWrapper = new ProcessWrapper(process, this, _logger)) { @@ -783,7 +761,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath); - _logger.Error(msg); + _logger.LogError(msg); throw new Exception(msg); } @@ -877,7 +855,7 @@ namespace MediaBrowser.MediaEncoding.Encoder ErrorDialog = false }); - _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments); + _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments); await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -929,7 +907,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument); - _logger.Error(msg); + _logger.LogError(msg); throw new Exception(msg); } @@ -961,7 +939,7 @@ namespace MediaBrowser.MediaEncoding.Encoder IProgress progress, CancellationToken cancellationToken) { - _logger.Error("EncodeVideo"); + _logger.LogError("EncodeVideo"); var job = await new VideoEncoder(this, _logger, ConfigurationManager, @@ -999,18 +977,18 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.Error("Error in WaitForExit", ex); + _logger.LogError(ex, "Error in WaitForExit"); } try { - _logger.Info("Killing ffmpeg process"); + _logger.LogInformation("Killing ffmpeg process"); process.Process.Kill(); } catch (Exception ex) { - _logger.ErrorException("Error killing process", ex); + _logger.LogError(ex, "Error killing process"); } } diff --git a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs index 96c126923..732b5bf84 100644 --- a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Threading.Tasks; @@ -63,4 +63,4 @@ namespace MediaBrowser.MediaEncoding.Encoder } } -} \ No newline at end of file +} diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index 64ab6831c..d9d2b4bf9 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -1,33 +1,20 @@  + netstandard2.0 false + - - Properties\SharedVersion.cs - + + - - {88ae38df-19d7-406f-a6a9-09527719a21e} - BDInfo - - - {9142eefa-7570-41e1-bfcc-468bb571af2f} - MediaBrowser.Common - - - {17e1f4e6-8abd-4fe5-9ecf-43d4b6087ba2} - MediaBrowser.Controller - - - {7eeeb4bb-f3e8-48fc-b4c5-70f0fff8329b} - MediaBrowser.Model - - - {4a4402d4-e910-443b-b8fc-2c18286a2ca0} - OpenSubtitlesHandler - + + + + + + diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 0a3532b8c..d0ccef2f8 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -13,7 +13,7 @@ using MediaBrowser.Model.IO; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; namespace MediaBrowser.MediaEncoding.Probing @@ -1351,11 +1351,11 @@ namespace MediaBrowser.MediaEncoding.Probing { video.Timestamp = GetMpegTimestamp(video.Path); - _logger.Debug("Video has {0} timestamp", video.Timestamp); + _logger.LogDebug("Video has {timestamp} timestamp", video.Timestamp); } catch (Exception ex) { - _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path); + _logger.LogError(ex, "Error extracting timestamp info from {path}", video.Path); video.Timestamp = null; } } diff --git a/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs b/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs index 3954897ca..2d29f29e3 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs @@ -15,9 +15,9 @@ using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; using OpenSubtitlesHandler; namespace MediaBrowser.MediaEncoding.Subtitles @@ -34,9 +34,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles private readonly IJsonSerializer _json; private readonly IFileSystem _fileSystem; - public OpenSubtitleDownloader(ILogManager logManager, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json, IFileSystem fileSystem) + public OpenSubtitleDownloader(ILoggerFactory loggerFactory, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json, IFileSystem fileSystem) { - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _httpClient = httpClient; _config = config; _encryption = encryption; @@ -208,7 +208,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var result = OpenSubtitles.GetSubLanguages("en"); if (!(result is MethodResponseGetSubLanguages)) { - _logger.Error("Invalid response type"); + _logger.LogError("Invalid response type"); return new List(); } @@ -243,19 +243,19 @@ namespace MediaBrowser.MediaEncoding.Subtitles case VideoContentType.Episode: if (!request.IndexNumber.HasValue || !request.ParentIndexNumber.HasValue || string.IsNullOrEmpty(request.SeriesName)) { - _logger.Debug("Episode information missing"); + _logger.LogDebug("Episode information missing"); return new List(); } break; case VideoContentType.Movie: if (string.IsNullOrEmpty(request.Name)) { - _logger.Debug("Movie name missing"); + _logger.LogDebug("Movie name missing"); return new List(); } if (string.IsNullOrWhiteSpace(imdbIdText) || !long.TryParse(imdbIdText.TrimStart('t'), NumberStyles.Any, _usCulture, out imdbId)) { - _logger.Debug("Imdb id missing"); + _logger.LogDebug("Imdb id missing"); return new List(); } break; @@ -263,7 +263,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (string.IsNullOrEmpty(request.MediaPath)) { - _logger.Debug("Path Missing"); + _logger.LogDebug("Path Missing"); return new List(); } @@ -300,7 +300,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var result = await OpenSubtitles.SearchSubtitlesAsync(parms.ToArray(), cancellationToken).ConfigureAwait(false); if (!(result is MethodResponseSubtitleSearch)) { - _logger.Error("Invalid response type"); + _logger.LogError("Invalid response type"); return new List(); } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs index de6d7bc72..7ca8aa1fd 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs @@ -1,5 +1,5 @@ using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -50,7 +50,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { // This occurs when subtitle text has an empty line as part of the text. // Need to adjust the break statement below to resolve this. - _logger.Warn("Unrecognized line in srt: {0}", line); + _logger.LogWarning("Unrecognized line in srt: {0}", line); continue; } subEvent.StartPositionTicks = GetTicks(time[0]); diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index d565ff3e2..43f775392 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -190,7 +190,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false); var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, language, true); - _logger.Debug("charset {0} detected for {1}", charset ?? "null", path); + _logger.LogDebug("charset {0} detected for {1}", charset ?? "null", path); if (!string.IsNullOrEmpty(charset)) { @@ -423,7 +423,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles ErrorDialog = false }); - _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); try { @@ -431,7 +431,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (Exception ex) { - _logger.ErrorException("Error starting ffmpeg", ex); + _logger.LogError(ex, "Error starting ffmpeg"); throw; } @@ -442,13 +442,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles { try { - _logger.Info("Killing ffmpeg subtitle conversion process"); + _logger.LogInformation("Killing ffmpeg subtitle conversion process"); process.Kill(); } catch (Exception ex) { - _logger.ErrorException("Error killing subtitle conversion process", ex); + _logger.LogError(ex, "Error killing subtitle conversion process"); } } @@ -466,12 +466,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles { try { - _logger.Info("Deleting converted subtitle due to failure: ", outputPath); + _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath); _fileSystem.DeleteFile(outputPath); } catch (IOException ex) { - _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath); + _logger.LogError(ex, "Error deleting converted subtitle {0}", outputPath); } } } @@ -484,13 +484,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles { var msg = string.Format("ffmpeg subtitle conversion failed for {0}", inputPath); - _logger.Error(msg); + _logger.LogError(msg); throw new Exception(msg); } await SetAssFont(outputPath).ConfigureAwait(false); - _logger.Info("ffmpeg subtitle conversion succeeded for {0}", inputPath); + _logger.LogInformation("ffmpeg subtitle conversion succeeded for {0}", inputPath); } /// @@ -553,7 +553,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles ErrorDialog = false }); - _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); try { @@ -561,7 +561,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (Exception ex) { - _logger.ErrorException("Error starting ffmpeg", ex); + _logger.LogError(ex, "Error starting ffmpeg"); throw; } @@ -572,13 +572,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles { try { - _logger.Info("Killing ffmpeg subtitle extraction process"); + _logger.LogInformation("Killing ffmpeg subtitle extraction process"); process.Kill(); } catch (Exception ex) { - _logger.ErrorException("Error killing subtitle extraction process", ex); + _logger.LogError(ex, "Error killing subtitle extraction process"); } } @@ -594,7 +594,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles try { - _logger.Info("Deleting extracted subtitle due to failure: {0}", outputPath); + _logger.LogInformation("Deleting extracted subtitle due to failure: {0}", outputPath); _fileSystem.DeleteFile(outputPath); } catch (FileNotFoundException) @@ -603,7 +603,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (IOException ex) { - _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath); + _logger.LogError(ex, "Error deleting extracted subtitle {0}", outputPath); } } else if (!_fileSystem.FileExists(outputPath)) @@ -615,7 +615,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath); - _logger.Error(msg); + _logger.LogError(msg); throw new Exception(msg); } @@ -623,7 +623,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath); - _logger.Info(msg); + _logger.LogInformation(msg); } if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase)) @@ -639,7 +639,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// Task. private async Task SetAssFont(string file) { - _logger.Info("Setting ass font within {0}", file); + _logger.LogInformation("Setting ass font within {0}", file); string text; Encoding encoding; @@ -659,11 +659,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (!string.Equals(text, newText)) { using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var writer = new StreamWriter(fileStream, encoding)) { - using (var writer = new StreamWriter(fileStream, encoding)) - { - writer.Write(newText); - } + writer.Write(newText); } } } @@ -698,7 +696,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, language, true); - _logger.Debug("charset {0} detected for {1}", charset ?? "null", path); + _logger.LogDebug("charset {0} detected for {1}", charset ?? "null", path); return charset; } @@ -730,4 +728,4 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Model/Activity/ActivityLogEntry.cs b/MediaBrowser.Model/Activity/ActivityLogEntry.cs index 1f4bff10d..a61ebc268 100644 --- a/MediaBrowser.Model/Activity/ActivityLogEntry.cs +++ b/MediaBrowser.Model/Activity/ActivityLogEntry.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; namespace MediaBrowser.Model.Activity @@ -63,6 +63,6 @@ namespace MediaBrowser.Model.Activity /// Gets or sets the log severity. /// /// The log severity. - public LogSeverity Severity { get; set; } + public LogLevel Severity { get; set; } } } diff --git a/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs b/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs index b5b0101cb..f84735bed 100644 --- a/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs +++ b/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs @@ -9,6 +9,7 @@ namespace MediaBrowser.Model.Configuration /// public class BaseApplicationConfiguration { + // TODO: @bond Remove? /// /// Gets or sets a value indicating whether [enable debug level logging]. /// @@ -21,6 +22,7 @@ namespace MediaBrowser.Model.Configuration /// true if [enable auto update]; otherwise, false. public bool EnableAutoUpdate { get; set; } + // TODO: @bond Remove? /// /// The number of days we should retain log files /// diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 58a839167..5effba26b 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -221,7 +221,7 @@ namespace MediaBrowser.Model.Configuration HttpsPortNumber = DefaultHttpsPort; EnableHttps = true; EnableDashboardResponseCaching = true; - EnableAnonymousUsageReporting = true; + EnableAnonymousUsageReporting = false; EnableCaseSensitiveItemIds = true; EnableAutomaticRestart = true; @@ -246,7 +246,7 @@ namespace MediaBrowser.Model.Configuration SortRemoveCharacters = new[] { ",", "&", "-", "{", "}", "'" }; SortRemoveWords = new[] { "the", "a", "an" }; - UICulture = "en-us"; + UICulture = "en-US"; MetadataOptions = new[] { @@ -310,4 +310,4 @@ namespace MediaBrowser.Model.Configuration public string From { get; set; } public string To { get; set; } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs index b6f329387..81d58336b 100644 --- a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs +++ b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs @@ -101,7 +101,7 @@ namespace MediaBrowser.Model.Dlna { list.Add(MediaFormatProfile.MPEG_TS_JP_T); } - return list.ToArray(list.Count); + return list.ToArray(); } if (StringHelper.EqualsIgnoreCase(videoCodec, "h264")) { diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 840abf618..41306b4c3 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -1,7 +1,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Session; using System; @@ -528,7 +528,7 @@ namespace MediaBrowser.Model.Dlna { transcodeReasons.InsertRange(0, GetTranscodeReasonsFromDirectPlayProfile(item, null, audioStream, options.Profile.DirectPlayProfiles)); - _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}", + _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}", options.Profile.Name ?? "Unknown Profile", item.Path ?? "Unknown path"); } @@ -732,7 +732,7 @@ namespace MediaBrowser.Model.Dlna bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || directPlayEligibilityResult.Item1); bool isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || directStreamEligibilityResult.Item1); - _logger.Info("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}", + _logger.LogInformation("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}", options.Profile.Name ?? "Unknown Profile", item.Path ?? "Unknown path", isEligibleForDirectPlay, @@ -1022,7 +1022,7 @@ namespace MediaBrowser.Model.Dlna if (directPlay == null) { - _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}", + _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}", profile.Name ?? "Unknown Profile", mediaSource.Path ?? "Unknown path"); @@ -1188,7 +1188,7 @@ namespace MediaBrowser.Model.Dlna private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource) { - _logger.Info("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}", + _logger.LogInformation("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}", type, profile.Name ?? "Unknown Profile", condition.Property, @@ -1210,7 +1210,7 @@ namespace MediaBrowser.Model.Dlna if (subtitleProfile.Method != SubtitleDeliveryMethod.External && subtitleProfile.Method != SubtitleDeliveryMethod.Embed) { - _logger.Info("Not eligible for {0} due to unsupported subtitles", playMethod); + _logger.LogInformation("Not eligible for {0} due to unsupported subtitles", playMethod); return new ValueTuple(false, TranscodeReason.SubtitleCodecNotSupported); } } @@ -1397,7 +1397,7 @@ namespace MediaBrowser.Model.Dlna if (itemBitrate > requestedMaxBitrate) { - _logger.Info("Bitrate exceeds " + playMethod + " limit: media bitrate: {0}, max bitrate: {1}", itemBitrate.ToString(CultureInfo.InvariantCulture), requestedMaxBitrate.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Bitrate exceeds " + playMethod + " limit: media bitrate: {0}, max bitrate: {1}", itemBitrate.ToString(CultureInfo.InvariantCulture), requestedMaxBitrate.ToString(CultureInfo.InvariantCulture)); return false; } diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 46a1cd68b..c927cd31c 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -186,7 +186,7 @@ namespace MediaBrowser.Model.Dlna list.Add(string.Format("{0}={1}", pair.Name, encodedValue)); } - string queryString = string.Join("&", list.ToArray(list.Count)); + string queryString = string.Join("&", list.ToArray()); return GetUrl(baseUrl, queryString); } diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs index fc208459d..35369fbbb 100644 --- a/MediaBrowser.Model/Entities/MediaStream.cs +++ b/MediaBrowser.Model/Entities/MediaStream.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Collections.Generic; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Extensions; @@ -104,7 +105,7 @@ namespace MediaBrowser.Model.Entities attributes.Add("Default"); } - return string.Join(" ", attributes.ToArray(attributes.Count)); + return string.Join(" ", attributes.ToArray()); } if (Type == MediaStreamType.Video) @@ -123,7 +124,7 @@ namespace MediaBrowser.Model.Entities attributes.Add(Codec.ToUpper()); } - return string.Join(" ", attributes.ToArray(attributes.Count)); + return string.Join(" ", attributes.ToArray()); } if (Type == MediaStreamType.Subtitle) @@ -154,7 +155,7 @@ namespace MediaBrowser.Model.Entities attributes.Add("Forced"); } - string name = string.Join(" ", attributes.ToArray(attributes.Count)); + string name = string.Join(" ", attributes.ToArray()); return name; } diff --git a/MediaBrowser.Model/Extensions/LinqExtensions.cs b/MediaBrowser.Model/Extensions/LinqExtensions.cs index 09ace42e8..1223e689e 100644 --- a/MediaBrowser.Model/Extensions/LinqExtensions.cs +++ b/MediaBrowser.Model/Extensions/LinqExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; +// TODO: @bond Remove namespace MediaBrowser.Model.Extensions { // MoreLINQ - Extensions to LINQ to Objects @@ -42,19 +43,6 @@ namespace MediaBrowser.Model.Extensions return source.DistinctBy(keySelector, null); } - public static TSource[] ToArray(this IEnumerable source, int count) - { - if (source == null) throw new ArgumentNullException("source"); - if (count < 0) throw new ArgumentOutOfRangeException("count"); - var array = new TSource[count]; - int i = 0; - foreach (var item in source) - { - array[i++] = item; - } - return array; - } - /// /// Returns all distinct elements of the given source, where "distinctness" /// is determined via a projection and the specified comparer for the projected type. diff --git a/MediaBrowser.Model/Logging/IConsoleLogger.cs b/MediaBrowser.Model/Logging/IConsoleLogger.cs deleted file mode 100644 index a8c282d65..000000000 --- a/MediaBrowser.Model/Logging/IConsoleLogger.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace MediaBrowser.Model.Logging -{ - public interface IConsoleLogger - { - void WriteLine(string message); - } -} diff --git a/MediaBrowser.Model/Logging/ILogManager.cs b/MediaBrowser.Model/Logging/ILogManager.cs deleted file mode 100644 index e6a10cf18..000000000 --- a/MediaBrowser.Model/Logging/ILogManager.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Model.Logging -{ - /// - /// Interface ILogManager - /// - public interface ILogManager - { - /// - /// Gets or sets the log level. - /// - /// The log level. - LogSeverity LogSeverity { get; set; } - - /// - /// Gets or sets the exception message prefix. - /// - /// The exception message prefix. - string ExceptionMessagePrefix { get; set; } - - /// - /// Gets the logger. - /// - /// The name. - /// ILogger. - ILogger GetLogger(string name); - - /// - /// Reloads the logger. - /// - Task ReloadLogger(LogSeverity severity, CancellationToken cancellationToken); - - /// - /// Occurs when [logger loaded]. - /// - event EventHandler LoggerLoaded; - - /// - /// Flushes this instance. - /// - void Flush(); - - /// - /// Adds the console output. - /// - void AddConsoleOutput(); - - /// - /// Removes the console output. - /// - void RemoveConsoleOutput(); - } -} diff --git a/MediaBrowser.Model/Logging/ILogger.cs b/MediaBrowser.Model/Logging/ILogger.cs deleted file mode 100644 index be9d6fc50..000000000 --- a/MediaBrowser.Model/Logging/ILogger.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Text; - -namespace MediaBrowser.Model.Logging -{ - /// - /// Interface ILogger - /// - public interface ILogger - { - /// - /// Infoes the specified message. - /// - /// The message. - /// The param list. - void Info(string message, params object[] paramList); - - /// - /// Errors the specified message. - /// - /// The message. - /// The param list. - void Error(string message, params object[] paramList); - - /// - /// Warns the specified message. - /// - /// The message. - /// The param list. - void Warn(string message, params object[] paramList); - - /// - /// Debugs the specified message. - /// - /// The message. - /// The param list. - void Debug(string message, params object[] paramList); - - /// - /// Fatals the specified message. - /// - /// The message. - /// The param list. - void Fatal(string message, params object[] paramList); - - /// - /// Fatals the exception. - /// - /// The message. - /// The exception. - /// The param list. - void FatalException(string message, Exception exception, params object[] paramList); - - /// - /// Logs the exception. - /// - /// The message. - /// The exception. - /// The param list. - void ErrorException(string message, Exception exception, params object[] paramList); - - /// - /// Logs the multiline. - /// - /// The message. - /// The severity. - /// Content of the additional. - void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent); - - /// - /// Logs the specified severity. - /// - /// The severity. - /// The message. - /// The parameter list. - void Log(LogSeverity severity, string message, params object[] paramList); - } -} diff --git a/MediaBrowser.Model/Logging/LogHelper.cs b/MediaBrowser.Model/Logging/LogHelper.cs deleted file mode 100644 index cf1c02186..000000000 --- a/MediaBrowser.Model/Logging/LogHelper.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Text; - -namespace MediaBrowser.Model.Logging -{ - /// - /// Class LogHelper - /// - public static class LogHelper - { - /// - /// Gets the log message. - /// - /// The exception. - /// StringBuilder. - public static StringBuilder GetLogMessage(Exception exception) - { - if (exception == null) - { - throw new ArgumentNullException("exception"); - } - - var messageText = new StringBuilder(); - - messageText.AppendLine(exception.ToString()); - - messageText.AppendLine(exception.GetType().FullName); - - LogExceptionData(messageText, exception); - - messageText.AppendLine(exception.StackTrace ?? "No Stack Trace Available"); - - // Log the InnerExceptions, if any - AppendInnerExceptions(messageText, exception); - - messageText.AppendLine(string.Empty); - - return messageText; - } - - /// - /// Appends the inner exceptions. - /// - /// The message text. - /// The e. - private static void AppendInnerExceptions(StringBuilder messageText, Exception e) - { - var aggregate = e as AggregateException; - - if (aggregate != null && aggregate.InnerExceptions != null) - { - foreach (var ex in aggregate.InnerExceptions) - { - AppendInnerException(messageText, ex); - AppendInnerExceptions(messageText, ex); - } - } - - else if (e.InnerException != null) - { - AppendInnerException(messageText, e.InnerException); - AppendInnerExceptions(messageText, e.InnerException); - } - } - - /// - /// Appends the inner exception. - /// - /// The message text. - /// The e. - private static void AppendInnerException(StringBuilder messageText, Exception e) - { - messageText.AppendLine("InnerException: " + e.GetType().FullName); - messageText.AppendLine(e.ToString()); - - LogExceptionData(messageText, e); - - if (e.StackTrace != null) - { - messageText.AppendLine(e.StackTrace); - } - } - - /// - /// Logs the exception data. - /// - /// The message text. - /// The e. - private static void LogExceptionData(StringBuilder messageText, Exception e) - { - foreach (var key in e.Data.Keys) - { - messageText.AppendLine(key + ": " + e.Data[key]); - } - } - } -} diff --git a/MediaBrowser.Model/Logging/LogSeverity.cs b/MediaBrowser.Model/Logging/LogSeverity.cs deleted file mode 100644 index ae0487289..000000000 --- a/MediaBrowser.Model/Logging/LogSeverity.cs +++ /dev/null @@ -1,30 +0,0 @@ - -namespace MediaBrowser.Model.Logging -{ - /// - /// Enum LogSeverity - /// - public enum LogSeverity - { - /// - /// The info - /// - Info, - /// - /// The debug - /// - Debug, - /// - /// The warn - /// - Warn, - /// - /// The error - /// - Error, - /// - /// The fatal - /// - Fatal - } -} diff --git a/MediaBrowser.Model/Logging/NullLogger.cs b/MediaBrowser.Model/Logging/NullLogger.cs deleted file mode 100644 index d211d2567..000000000 --- a/MediaBrowser.Model/Logging/NullLogger.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Text; - -namespace MediaBrowser.Model.Logging -{ - public class NullLogger : ILogger - { - public void Info(string message, params object[] paramList) - { - } - - public void Error(string message, params object[] paramList) - { - } - - public void Warn(string message, params object[] paramList) - { - } - - public void Debug(string message, params object[] paramList) - { - } - - public void Fatal(string message, params object[] paramList) - { - } - - public void FatalException(string message, Exception exception, params object[] paramList) - { - } - - public void Log(LogSeverity severity, string message, params object[] paramList) - { - } - - public void ErrorException(string message, Exception exception, params object[] paramList) - { - } - - public void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent) - { - } - } -} diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 1b1a24b68..a5b2f4083 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -5,6 +5,10 @@ false + + + + diff --git a/MediaBrowser.Model/Services/HttpUtility.cs b/MediaBrowser.Model/Services/HttpUtility.cs index 5cc0cc37d..f8fd96801 100644 --- a/MediaBrowser.Model/Services/HttpUtility.cs +++ b/MediaBrowser.Model/Services/HttpUtility.cs @@ -2,8 +2,6 @@ using System.Collections; using System.Collections.Generic; using System.Text; -using MediaBrowser.Model.Services; -using MediaBrowser.Model.Extensions; namespace MediaBrowser.Model.Services { @@ -586,7 +584,7 @@ namespace MediaBrowser.Model.Services WriteCharBytes(bytes, ch, e); } - byte[] buf = bytes.ToArray(bytes.Count); + byte[] buf = bytes.ToArray(); bytes = null; return e.GetString(buf, 0, buf.Length); diff --git a/MediaBrowser.Model/Services/QueryParamCollection.cs b/MediaBrowser.Model/Services/QueryParamCollection.cs index 6f8a76598..4dd4303a8 100644 --- a/MediaBrowser.Model/Services/QueryParamCollection.cs +++ b/MediaBrowser.Model/Services/QueryParamCollection.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Extensions; namespace MediaBrowser.Model.Services { @@ -221,7 +220,7 @@ namespace MediaBrowser.Model.Services public override String ToString() { - var vals = this.Select(GetQueryStringValue).ToArray(this.Count); + var vals = this.Select(GetQueryStringValue).ToArray(); return string.Join("&", vals); } diff --git a/MediaBrowser.Model/Tasks/ITaskTrigger.cs b/MediaBrowser.Model/Tasks/ITaskTrigger.cs index 7c804348a..9db0041b4 100644 --- a/MediaBrowser.Model/Tasks/ITaskTrigger.cs +++ b/MediaBrowser.Model/Tasks/ITaskTrigger.cs @@ -1,6 +1,6 @@ using System; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Model.Tasks { @@ -29,4 +29,4 @@ namespace MediaBrowser.Model.Tasks /// void Stop(); } -} \ No newline at end of file +} diff --git a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs index 834ec6cd3..707e942f3 100644 --- a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs +++ b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Providers/Books/BookMetadataService.cs b/MediaBrowser.Providers/Books/BookMetadataService.cs index 68b96486a..a2143982a 100644 --- a/MediaBrowser.Providers/Books/BookMetadataService.cs +++ b/MediaBrowser.Providers/Books/BookMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs index 78791906a..7cfae3a12 100644 --- a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs +++ b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Linq; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs index 634329177..0369e8ca1 100644 --- a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs +++ b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Movies; diff --git a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs index b22db559e..6b371fef9 100644 --- a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs +++ b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Chapters/ChapterManager.cs b/MediaBrowser.Providers/Chapters/ChapterManager.cs index 3d0c7c964..7eb650cca 100644 --- a/MediaBrowser.Providers/Chapters/ChapterManager.cs +++ b/MediaBrowser.Providers/Chapters/ChapterManager.cs @@ -10,7 +10,7 @@ using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading; diff --git a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs index e472a23c4..bf35cd105 100644 --- a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs +++ b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; namespace MediaBrowser.Providers.Folders diff --git a/MediaBrowser.Providers/Folders/FolderMetadataService.cs b/MediaBrowser.Providers/Folders/FolderMetadataService.cs index 687dac919..514788261 100644 --- a/MediaBrowser.Providers/Folders/FolderMetadataService.cs +++ b/MediaBrowser.Providers/Folders/FolderMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs index 951794961..14e0c3de6 100644 --- a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs +++ b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs b/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs index edde0f5e3..8cc11701e 100644 --- a/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs +++ b/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Games/GameMetadataService.cs b/MediaBrowser.Providers/Games/GameMetadataService.cs index 67becbf58..4a56cc03b 100644 --- a/MediaBrowser.Providers/Games/GameMetadataService.cs +++ b/MediaBrowser.Providers/Games/GameMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Games/GameSystemMetadataService.cs b/MediaBrowser.Providers/Games/GameSystemMetadataService.cs index 474dd2fcf..25fdfb713 100644 --- a/MediaBrowser.Providers/Games/GameSystemMetadataService.cs +++ b/MediaBrowser.Providers/Games/GameSystemMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Genres/GenreMetadataService.cs b/MediaBrowser.Providers/Genres/GenreMetadataService.cs index 88fba1854..8d764dbb3 100644 --- a/MediaBrowser.Providers/Genres/GenreMetadataService.cs +++ b/MediaBrowser.Providers/Genres/GenreMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs b/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs index dfb0c58ad..722de4dee 100644 --- a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs +++ b/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs index c4d0c4929..6790f9b33 100644 --- a/MediaBrowser.Providers/Manager/ImageSaver.cs +++ b/MediaBrowser.Providers/Manager/ImageSaver.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using System; using System.Collections.Generic; @@ -164,7 +164,7 @@ namespace MediaBrowser.Providers.Manager { var currentPath = currentImagePath; - _logger.Info("Deleting previous image {0}", currentPath); + _logger.LogInformation("Deleting previous image {0}", currentPath); _libraryMonitor.ReportFileSystemChangeBeginning(currentPath); @@ -197,7 +197,7 @@ namespace MediaBrowser.Providers.Manager if (retry) { - _logger.Error("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath); + _logger.LogError("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath); } else { @@ -211,7 +211,7 @@ namespace MediaBrowser.Providers.Manager if (retry) { - _logger.Error("IOException saving to {0}. {2}. Will retry saving to {1}", path, retryPath, ex.Message); + _logger.LogError(ex, "IOException saving to {0}. Will retry saving to {1}", path, retryPath); } else { @@ -233,7 +233,7 @@ namespace MediaBrowser.Providers.Manager /// Task. private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken) { - _logger.Debug("Saving image to {0}", path); + _logger.LogDebug("Saving image to {0}", path); var parentFolder = _fileSystem.GetDirectoryName(path); @@ -271,7 +271,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.Error("Error setting hidden attribute on {0} - {1}", path, ex.Message); + _logger.LogError(ex, "Error setting hidden attribute on {0}", path); } } @@ -551,7 +551,7 @@ namespace MediaBrowser.Providers.Manager { list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension)); } - return list.ToArray(list.Count); + return list.ToArray(); } if (type == ImageType.Primary) diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index c80d43841..fc30374b3 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; using System; @@ -126,7 +126,7 @@ namespace MediaBrowser.Providers.Manager if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType))) { - _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name); + _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name); var response = await provider.GetImage(item, imageType, cancellationToken).ConfigureAwait(false); @@ -136,7 +136,7 @@ namespace MediaBrowser.Providers.Manager { if (response.Protocol == MediaProtocol.Http) { - _logger.Debug("Setting image url into item {0}", item.Id); + _logger.LogDebug("Setting image url into item {0}", item.Id); item.SetImage(new ItemImageInfo { Path = response.Path, @@ -173,7 +173,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { result.ErrorMessage = ex.Message; - _logger.ErrorException("Error in {0}", ex, provider.Name); + _logger.LogError(ex, "Error in {provider}", provider.Name); } } @@ -264,7 +264,7 @@ namespace MediaBrowser.Providers.Manager return; } - _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name); + _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name); var images = await _providerManager.GetAvailableRemoteImages(item, new RemoteImageQuery { @@ -310,7 +310,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { result.ErrorMessage = ex.Message; - _logger.ErrorException("Error in {0}", ex, provider.Name); + _logger.LogError(ex, "Error in {provider}", provider.Name); } } @@ -577,7 +577,7 @@ namespace MediaBrowser.Providers.Manager } catch (IOException ex) { - _logger.ErrorException("Error examining images", ex); + _logger.LogError(ex, "Error examining images"); } } @@ -586,7 +586,7 @@ namespace MediaBrowser.Providers.Manager } catch (HttpException ex) { - // Sometimes providers send back bad url's. Just move onto the next image + // Sometimes providers send back bad urls. Just move onto the next image if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound) { continue; @@ -596,4 +596,4 @@ namespace MediaBrowser.Providers.Manager } } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 57711d3b6..e26004923 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -46,7 +46,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - Logger.ErrorException("Error getting file {0}", ex, path); + Logger.LogError(ex, "Error getting file {path}", path); return null; } } @@ -73,7 +73,7 @@ namespace MediaBrowser.Providers.Manager if (requiresRefresh) { - Logger.Debug("Refreshing {0} {1} because item.RequiresRefresh() returned true", typeof(TItemType).Name, item.Path ?? item.Name); + Logger.LogDebug("Refreshing {0} {1} because item.RequiresRefresh() returned true", typeof(TItemType).Name, item.Path ?? item.Name); } } @@ -96,7 +96,7 @@ namespace MediaBrowser.Providers.Manager localImagesFailed = true; if (!(item is IItemByName)) { - Logger.ErrorException("Error validating images for {0}", ex, item.Path ?? item.Name ?? "Unknown name"); + Logger.LogError(ex, "Error validating images for {0}", item.Path ?? item.Name ?? "Unknown name"); } } @@ -268,7 +268,7 @@ namespace MediaBrowser.Providers.Manager // } // catch (Exception ex) // { - // Logger.ErrorException("Error in AddPersonImage", ex); + // Logger.LogError(ex, "Error in AddPersonImage"); // } //} @@ -728,7 +728,7 @@ namespace MediaBrowser.Providers.Manager foreach (var provider in providers.OfType>().ToList()) { var providerName = provider.GetType().Name; - Logger.Debug("Running {0} for {1}", providerName, logName); + Logger.LogDebug("Running {0} for {1}", providerName, logName); var itemInfo = new ItemInfo(item); @@ -759,7 +759,7 @@ namespace MediaBrowser.Providers.Manager break; } - Logger.Debug("{0} returned no metadata for {1}", providerName, logName); + Logger.LogDebug("{0} returned no metadata for {1}", providerName, logName); } catch (OperationCanceledException) { @@ -767,7 +767,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - Logger.ErrorException("Error in {0}", ex, provider.Name); + Logger.LogError(ex, "Error in {provider}", provider.Name); // If a local provider fails, consider that a failure refreshResult.ErrorMessage = ex.Message; @@ -826,7 +826,7 @@ namespace MediaBrowser.Providers.Manager private async Task RunCustomProvider(ICustomMetadataProvider provider, TItemType item, string logName, MetadataRefreshOptions options, RefreshResult refreshResult, CancellationToken cancellationToken) { - Logger.Debug("Running {0} for {1}", provider.GetType().Name, logName); + Logger.LogDebug("Running {0} for {1}", provider.GetType().Name, logName); try { @@ -839,7 +839,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { refreshResult.ErrorMessage = ex.Message; - Logger.ErrorException("Error in {0}", ex, provider.Name); + Logger.LogError(ex, "Error in {provider}", provider.Name); } } @@ -857,7 +857,7 @@ namespace MediaBrowser.Providers.Manager foreach (var provider in providers) { var providerName = provider.GetType().Name; - Logger.Debug("Running {0} for {1}", providerName, logName); + Logger.LogDebug("Running {0} for {1}", providerName, logName); if (id != null && !tmpDataMerged) { @@ -880,7 +880,7 @@ namespace MediaBrowser.Providers.Manager } else { - Logger.Debug("{0} returned no metadata for {1}", providerName, logName); + Logger.LogDebug("{0} returned no metadata for {1}", providerName, logName); } } catch (OperationCanceledException) @@ -891,7 +891,7 @@ namespace MediaBrowser.Providers.Manager { refreshResult.Failures++; refreshResult.ErrorMessage = ex.Message; - Logger.ErrorException("Error in {0}", ex, provider.Name); + Logger.LogError(ex, "Error in {provider}", provider.Name); } } @@ -944,14 +944,14 @@ namespace MediaBrowser.Providers.Manager //if (hasChanged) //{ - // Logger.Debug("{0} reports change to {1}", changeMonitor.GetType().Name, item.Path ?? item.Name); + // logger.LogDebug("{0} reports change to {1}", changeMonitor.GetType().Name, item.Path ?? item.Name); //} return hasChanged; } catch (Exception ex) { - Logger.ErrorException("Error in {0}.HasChanged", ex, changeMonitor.GetType().Name); + Logger.LogError(ex, "Error in {0}.HasChanged", changeMonitor.GetType().Name); return false; } } diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 4c9312b83..8a9aae117 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -10,7 +10,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -79,9 +79,9 @@ namespace MediaBrowser.Providers.Manager /// /// Initializes a new instance of the class. /// - public ProviderManager(IHttpClient httpClient, ISubtitleManager subtitleManager, IServerConfigurationManager configurationManager, ILibraryMonitor libraryMonitor, ILogManager logManager, IFileSystem fileSystem, IServerApplicationPaths appPaths, Func libraryManagerFactory, IJsonSerializer json) + public ProviderManager(IHttpClient httpClient, ISubtitleManager subtitleManager, IServerConfigurationManager configurationManager, ILibraryMonitor libraryMonitor, ILoggerFactory loggerFactory, IFileSystem fileSystem, IServerApplicationPaths appPaths, Func libraryManagerFactory, IJsonSerializer json) { - _logger = logManager.GetLogger("ProviderManager"); + _logger = loggerFactory.CreateLogger("ProviderManager"); _httpClient = httpClient; ConfigurationManager = configurationManager; _libraryMonitor = libraryMonitor; @@ -144,7 +144,7 @@ namespace MediaBrowser.Providers.Manager return service.RefreshMetadata(item, options, cancellationToken); } - _logger.Error("Unable to find a metadata service for item of type " + item.GetType().Name); + _logger.LogError("Unable to find a metadata service for item of type {TypeName}", item.GetType().Name); return Task.FromResult(ItemUpdateType.None); } @@ -250,7 +250,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("{0} failed in GetImageInfos for type {1}", ex, provider.GetType().Name, item.GetType().Name); + _logger.LogError(ex, "{0} failed in GetImageInfos for type {1}", provider.GetType().Name, item.GetType().Name); return new List(); } } @@ -329,7 +329,11 @@ namespace MediaBrowser.Providers.Manager var options = GetMetadataOptions(item); var libraryOptions = _libraryManagerFactory().GetLibraryOptions(item); - return GetImageProviders(item, libraryOptions, options, new ImageRefreshOptions(new DirectoryService(_logger, _fileSystem)), includeDisabled).OfType(); + return GetImageProviders(item, libraryOptions, options, + new ImageRefreshOptions( + new DirectoryService(_logger, _fileSystem)), + includeDisabled) + .OfType(); } private bool CanRefresh(IMetadataProvider provider, BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, bool includeDisabled, bool forceEnableInternetMetadata) @@ -396,7 +400,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("{0} failed in Supports for type {1}", ex, provider.GetType().Name, item.GetType().Name); + _logger.LogError(ex, "{0} failed in Supports for type {1}", provider.GetType().Name, item.GetType().Name); return false; } } @@ -506,7 +510,11 @@ namespace MediaBrowser.Providers.Manager var libraryOptions = new LibraryOptions(); - var imageProviders = GetImageProviders(dummy, libraryOptions, options, new ImageRefreshOptions(new DirectoryService(_logger, _fileSystem)), true).ToList(); + var imageProviders = GetImageProviders(dummy, libraryOptions, options, + new ImageRefreshOptions( + new DirectoryService(_logger, _fileSystem)), + true) + .ToList(); var pluginList = summary.Plugins.ToList(); @@ -522,7 +530,7 @@ namespace MediaBrowser.Providers.Manager Type = MetadataPluginType.SubtitleFetcher })); - summary.Plugins = pluginList.ToArray(pluginList.Count); + summary.Plugins = pluginList.ToArray(); var supportedImageTypes = imageProviders.OfType() .SelectMany(i => i.GetSupportedImages(dummy)) @@ -620,7 +628,7 @@ namespace MediaBrowser.Providers.Manager foreach (var saver in savers.Where(i => IsSaverEnabledForItem(i, item, libraryOptions, updateType, false))) { - _logger.Debug("Saving {0} to {1}.", item.Path ?? item.Name, saver.Name); + _logger.LogDebug("Saving {0} to {1}.", item.Path ?? item.Name, saver.Name); var fileSaver = saver as IMetadataFileSaver; @@ -634,7 +642,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in {0} GetSavePath", ex, saver.Name); + _logger.LogError(ex, "Error in {0} GetSavePath", saver.Name); continue; } @@ -645,7 +653,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in metadata saver", ex); + _logger.LogError(ex, "Error in metadata saver"); } finally { @@ -660,7 +668,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in metadata saver", ex); + _logger.LogError(ex, "Error in metadata saver"); } } } @@ -723,7 +731,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in {0}.IsEnabledFor", ex, saver.Name); + _logger.LogError(ex, "Error in {0}.IsEnabledFor", saver.Name); return false; } } @@ -825,7 +833,7 @@ namespace MediaBrowser.Providers.Manager } } - //_logger.Debug("Returning search results {0}", _json.SerializeToString(resultList)); + //_logger.LogDebug("Returning search results {0}", _json.SerializeToString(resultList)); return resultList; } @@ -868,7 +876,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in {0}.Suports", ex, i.GetType().Name); + _logger.LogError(ex, "Error in {0}.Suports", i.GetType().Name); return false; } }); @@ -930,7 +938,7 @@ namespace MediaBrowser.Providers.Manager public void OnRefreshStart(BaseItem item) { - //_logger.Info("OnRefreshStart {0}", item.Id.ToString("N")); + //_logger.LogInformation("OnRefreshStart {0}", item.Id.ToString("N")); var id = item.Id; lock (_activeRefreshes) @@ -946,7 +954,7 @@ namespace MediaBrowser.Providers.Manager public void OnRefreshComplete(BaseItem item) { - //_logger.Info("OnRefreshComplete {0}", item.Id.ToString("N")); + //_logger.LogInformation("OnRefreshComplete {0}", item.Id.ToString("N")); lock (_activeRefreshes) { _activeRefreshes.Remove(item.Id); @@ -974,7 +982,7 @@ namespace MediaBrowser.Providers.Manager public void OnRefreshProgress(BaseItem item, double progress) { - //_logger.Info("OnRefreshProgress {0} {1}", item.Id.ToString("N"), progress); + //_logger.LogInformation("OnRefreshProgress {0} {1}", item.Id.ToString("N"), progress); var id = item.Id; lock (_activeRefreshes) @@ -1062,7 +1070,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error refreshing item", ex); + _logger.LogError(ex, "Error refreshing item"); } } @@ -1139,7 +1147,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error refreshing library", ex); + _logger.LogError(ex, "Error refreshing library"); } } @@ -1160,4 +1168,4 @@ namespace MediaBrowser.Providers.Manager } } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs index f7cbf7211..2827a3cc7 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs @@ -13,7 +13,7 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -71,7 +71,7 @@ namespace MediaBrowser.Providers.MediaInfo var file = directoryService.GetFile(path); if (file != null && file.LastWriteTimeUtc != item.DateModified) { - _logger.Debug("Refreshing {0} due to date modified timestamp change.", path); + _logger.LogDebug("Refreshing {0} due to date modified timestamp change.", path); return true; } } @@ -84,7 +84,7 @@ namespace MediaBrowser.Providers.MediaInfo if (!video.SubtitleFiles .SequenceEqual(_subtitleResolver.GetExternalSubtitleFiles(video, directoryService, false), StringComparer.Ordinal)) { - _logger.Debug("Refreshing {0} due to external subtitles change.", item.Path); + _logger.LogDebug("Refreshing {0} due to external subtitles change.", item.Path); return true; } } diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs index c7fc086be..c2fe392ab 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs @@ -14,7 +14,7 @@ using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; @@ -86,7 +86,7 @@ namespace MediaBrowser.Providers.MediaInfo if (streamFileNames.Length == 0) { - _logger.Error("No playable vobs found in dvd structure, skipping ffprobe."); + _logger.LogError("No playable vobs found in dvd structure, skipping ffprobe."); return ItemUpdateType.MetadataImport; } } @@ -101,7 +101,7 @@ namespace MediaBrowser.Providers.MediaInfo if (streamFileNames.Length == 0) { - _logger.Error("No playable vobs found in bluray structure, skipping ffprobe."); + _logger.LogError("No playable vobs found in bluray structure, skipping ffprobe."); return ItemUpdateType.MetadataImport; } } @@ -342,7 +342,7 @@ namespace MediaBrowser.Providers.MediaInfo } catch (Exception ex) { - _logger.ErrorException("Error getting BDInfo", ex); + _logger.LogError(ex, "Error getting BDInfo"); return null; } } @@ -611,4 +611,4 @@ namespace MediaBrowser.Providers.MediaInfo .Sum(); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs index 6b396967e..4c66f2b0a 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -176,7 +176,7 @@ namespace MediaBrowser.Providers.MediaInfo } catch (Exception ex) { - _logger.ErrorException("Error downloading subtitles", ex); + _logger.LogError(ex, "Error downloading subtitles"); } return false; diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs index 6b4181dfb..81abedeb9 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -148,7 +148,7 @@ namespace MediaBrowser.Providers.MediaInfo } catch (Exception ex) { - _logger.ErrorException("Error downloading subtitles for {0}", ex, video.Path); + _logger.LogError(ex, "Error downloading subtitles for {Path}", video.Path); } // Update progress diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs index 00ffe383f..baf913a77 100644 --- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; @@ -53,7 +53,7 @@ namespace MediaBrowser.Providers.MediaInfo // Can't extract if we didn't find a video stream in the file if (!video.DefaultVideoStreamIndex.HasValue) { - _logger.Info("Skipping image extraction due to missing DefaultVideoStreamIndex for {0}.", video.Path ?? string.Empty); + _logger.LogInformation("Skipping image extraction due to missing DefaultVideoStreamIndex for {0}.", video.Path ?? string.Empty); return Task.FromResult(new DynamicImageResponse { HasImage = false }); } diff --git a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs index 8a409f9cf..1fce01903 100644 --- a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs +++ b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -145,7 +145,7 @@ namespace MediaBrowser.Providers.Movies movie.ProductionLocations = movieData .production_countries .Select(i => i.name) - .ToArray(movieData.production_countries.Count); + .ToArray(); } movie.SetProviderId(MetadataProviders.Tmdb, movieData.id.ToString(_usCulture)); diff --git a/MediaBrowser.Providers/Movies/MovieDbProvider.cs b/MediaBrowser.Providers/Movies/MovieDbProvider.cs index e68ce19de..d967d7b62 100644 --- a/MediaBrowser.Providers/Movies/MovieDbProvider.cs +++ b/MediaBrowser.Providers/Movies/MovieDbProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using System; @@ -279,7 +279,7 @@ namespace MediaBrowser.Providers.Movies languages.Add("en"); } - return string.Join(",", languages.ToArray(languages.Count)); + return string.Join(",", languages.ToArray()); } public static string NormalizeLanguage(string language) @@ -287,7 +287,8 @@ namespace MediaBrowser.Providers.Movies if (!string.IsNullOrEmpty(language)) { // They require this to be uppercase - // https://emby.media/community/index.php?/topic/32454-fr-follow-tmdbs-new-language-api-update/?p=311148 + // Everything after the hyphen must be written in uppercase due to a way TMDB wrote their api. + // See here: https://www.themoviedb.org/talk/5119221d760ee36c642af4ad?page=3#56e372a0c3a3685a9e0019ab var parts = language.Split('-'); if (parts.Length == 2) @@ -378,7 +379,7 @@ namespace MediaBrowser.Providers.Movies !string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase)) { - _logger.Info("MovieDbProvider couldn't find meta for language " + language + ". Trying English..."); + _logger.LogInformation("MovieDbProvider couldn't find meta for language " + language + ". Trying English..."); url = string.Format(GetMovieInfo3, id, ApiKey) + "&language=en"; @@ -424,7 +425,7 @@ namespace MediaBrowser.Providers.Movies if (delayMs > 0) { - _logger.Debug("Throttling Tmdb by {0} ms", delayMs); + _logger.LogDebug("Throttling Tmdb by {0} ms", delayMs); await Task.Delay(Convert.ToInt32(delayMs)).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Movies/MovieDbSearch.cs b/MediaBrowser.Providers/Movies/MovieDbSearch.cs index 3b4a385d4..b332207e1 100644 --- a/MediaBrowser.Providers/Movies/MovieDbSearch.cs +++ b/MediaBrowser.Providers/Movies/MovieDbSearch.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using System; @@ -71,7 +71,7 @@ namespace MediaBrowser.Providers.Movies year = year ?? yearInName; } - _logger.Info("MovieDbProvider: Finding id for item: " + name); + _logger.LogInformation("MovieDbProvider: Finding id for item: " + name); var language = idInfo.MetadataLanguage.ToLower(); //nope - search for it diff --git a/MediaBrowser.Providers/Movies/MovieMetadataService.cs b/MediaBrowser.Providers/Movies/MovieMetadataService.cs index f0674ac9b..958153334 100644 --- a/MediaBrowser.Providers/Movies/MovieMetadataService.cs +++ b/MediaBrowser.Providers/Movies/MovieMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Music/AlbumMetadataService.cs b/MediaBrowser.Providers/Music/AlbumMetadataService.cs index 338fc1c6d..ae81545a6 100644 --- a/MediaBrowser.Providers/Music/AlbumMetadataService.cs +++ b/MediaBrowser.Providers/Music/AlbumMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Music/ArtistMetadataService.cs b/MediaBrowser.Providers/Music/ArtistMetadataService.cs index 7741a3f43..7dc4a8dfe 100644 --- a/MediaBrowser.Providers/Music/ArtistMetadataService.cs +++ b/MediaBrowser.Providers/Music/ArtistMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Music/AudioMetadataService.cs b/MediaBrowser.Providers/Music/AudioMetadataService.cs index f02eae19f..6952ee856 100644 --- a/MediaBrowser.Providers/Music/AudioMetadataService.cs +++ b/MediaBrowser.Providers/Music/AudioMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs index c676f9198..0dbc43313 100644 --- a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs @@ -3,7 +3,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -17,7 +17,6 @@ using System.Threading.Tasks; using System.Xml; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Xml; -using MediaBrowser.Model.Extensions; namespace MediaBrowser.Providers.Music { @@ -775,7 +774,7 @@ namespace MediaBrowser.Providers.Music } catch (Exception ex) { - _logger.ErrorException("Error getting music brainz info", ex); + _logger.LogError(ex, "Error getting music brainz info"); } } } @@ -813,7 +812,7 @@ namespace MediaBrowser.Providers.Music if (throttleMs > 0) { // MusicBrainz is extremely adamant about limiting to one request per second - _logger.Debug("Throttling MusicBrainz by {0}ms", throttleMs.ToString(CultureInfo.InvariantCulture)); + _logger.LogDebug("Throttling MusicBrainz by {0}ms", throttleMs.ToString(CultureInfo.InvariantCulture)); await Task.Delay(throttleMs, cancellationToken).ConfigureAwait(false); } @@ -846,4 +845,4 @@ namespace MediaBrowser.Providers.Music public int throttleMs { get; set; } } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs index 28504dbd7..54d68bfd5 100644 --- a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs +++ b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs index 3828f8d27..6c9bc526d 100644 --- a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs +++ b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs index 8c7ef71b6..39d9b39ee 100644 --- a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using System; diff --git a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs index 7af058bcd..dda1fc511 100644 --- a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs +++ b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; namespace MediaBrowser.Providers.People diff --git a/MediaBrowser.Providers/People/PersonMetadataService.cs b/MediaBrowser.Providers/People/PersonMetadataService.cs index bbfaa43b4..e32ecaa64 100644 --- a/MediaBrowser.Providers/People/PersonMetadataService.cs +++ b/MediaBrowser.Providers/People/PersonMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs index bff933ccf..f6d3724e9 100644 --- a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs +++ b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs index d7f4982e4..87529f93a 100644 --- a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs +++ b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs index da4873ca4..7bc2469a0 100644 --- a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs +++ b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs @@ -13,7 +13,7 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -169,7 +169,7 @@ namespace MediaBrowser.Providers.Playlists var file = directoryService.GetFile(path); if (file != null && file.LastWriteTimeUtc != item.DateModified) { - _logger.Debug("Refreshing {0} due to date modified timestamp change.", path); + _logger.LogDebug("Refreshing {0} due to date modified timestamp change.", path); return true; } } diff --git a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs index 1d6591792..9534a4759 100644 --- a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs +++ b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Providers/Studios/StudioMetadataService.cs b/MediaBrowser.Providers/Studios/StudioMetadataService.cs index 23953b0d3..0c07fb541 100644 --- a/MediaBrowser.Providers/Studios/StudioMetadataService.cs +++ b/MediaBrowser.Providers/Studios/StudioMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 071687c0f..2cf737511 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -101,7 +101,7 @@ namespace MediaBrowser.Providers.Subtitles } catch (Exception ex) { - _logger.ErrorException("Error downloading subtitles from {0}", ex, provider.Name); + _logger.LogError(ex, "Error downloading subtitles from {Provider}", provider.Name); } } return new RemoteSubtitleInfo[] { }; @@ -119,7 +119,7 @@ namespace MediaBrowser.Providers.Subtitles } catch (Exception ex) { - _logger.ErrorException("Error downloading subtitles from {0}", ex, i.Name); + _logger.LogError(ex, "Error downloading subtitles from {0}", i.Name); return new RemoteSubtitleInfo[] { }; } }); @@ -207,7 +207,7 @@ namespace MediaBrowser.Providers.Subtitles foreach (var savePath in savePaths) { - _logger.Info("Saving subtitles to {0}", savePath); + _logger.LogInformation("Saving subtitles to {0}", savePath); _monitor.ReportFileSystemChangeBeginning(savePath); diff --git a/MediaBrowser.Providers/TV/DummySeasonProvider.cs b/MediaBrowser.Providers/TV/DummySeasonProvider.cs index 4f528086e..797005c41 100644 --- a/MediaBrowser.Providers/TV/DummySeasonProvider.cs +++ b/MediaBrowser.Providers/TV/DummySeasonProvider.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Globalization; using System.Linq; using System.Threading; @@ -131,7 +131,7 @@ namespace MediaBrowser.Providers.TV _libraryManager.GetLibraryOptions(series).SeasonZeroDisplayName : (seasonNumber.HasValue ? string.Format(_localization.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value.ToString(_usCulture)) : _localization.GetLocalizedString("NameSeasonUnknown")); - _logger.Info("Creating Season {0} entry for {1}", seasonName, series.Name); + _logger.LogInformation("Creating Season {0} entry for {1}", seasonName, series.Name); var season = new Season { @@ -147,7 +147,7 @@ namespace MediaBrowser.Providers.TV series.AddChild(season, cancellationToken); - await season.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); return season; } @@ -192,7 +192,7 @@ namespace MediaBrowser.Providers.TV foreach (var seasonToRemove in seasonsToRemove) { - _logger.Info("Removing virtual season {0} {1}", series.Name, seasonToRemove.IndexNumber); + _logger.LogInformation("Removing virtual season {0} {1}", series.Name, seasonToRemove.IndexNumber); _libraryManager.DeleteItem(seasonToRemove, new DeleteOptions { diff --git a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs index cea907ca3..6292d9cf2 100644 --- a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs +++ b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Threading.Tasks; diff --git a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs index 6e469a041..19f3c07d2 100644 --- a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -217,7 +217,7 @@ namespace MediaBrowser.Providers.TV if (addMissingEpisodes) { // tvdb has a lot of nearly blank episodes - _logger.Info("Creating virtual missing episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2); + _logger.LogInformation("Creating virtual missing episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2); await AddEpisode(series, tuple.Item1, tuple.Item2, cancellationToken).ConfigureAwait(false); hasChanges = true; @@ -226,7 +226,7 @@ namespace MediaBrowser.Providers.TV else if (airDate.Value > now) { // tvdb has a lot of nearly blank episodes - _logger.Info("Creating virtual unaired episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2); + _logger.LogInformation("Creating virtual unaired episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2); await AddEpisode(series, tuple.Item1, tuple.Item2, cancellationToken).ConfigureAwait(false); hasChanges = true; @@ -414,7 +414,7 @@ namespace MediaBrowser.Providers.TV season.AddChild(episode, cancellationToken); - await episode.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + await episode.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); } /// diff --git a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs index e65c36d98..c62f58eb4 100644 --- a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Omdb; diff --git a/MediaBrowser.Providers/TV/SeasonMetadataService.cs b/MediaBrowser.Providers/TV/SeasonMetadataService.cs index a9a026db9..aad0e26a0 100644 --- a/MediaBrowser.Providers/TV/SeasonMetadataService.cs +++ b/MediaBrowser.Providers/TV/SeasonMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs index 338e7b4ed..1cb06efdf 100644 --- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs +++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System; using System.Collections.Generic; @@ -46,7 +46,7 @@ namespace MediaBrowser.Providers.TV } catch (Exception ex) { - Logger.ErrorException("Error in DummySeasonProvider", ex); + Logger.LogError(ex, "Error in DummySeasonProvider"); } } diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs index f6568510d..d9933ba2a 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Movies; @@ -25,8 +25,8 @@ namespace MediaBrowser.Providers.TV IRemoteImageProvider, IHasOrder { - public MovieDbEpisodeImageProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILogManager logManager) - : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, logManager) + public MovieDbEpisodeImageProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory) + : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory) {} public IEnumerable GetSupportedImages(BaseItem item) diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs index 31785ca9c..095ce0e17 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; @@ -27,8 +27,8 @@ namespace MediaBrowser.Providers.TV IRemoteMetadataProvider, IHasOrder { - public MovieDbEpisodeProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILogManager logManager) - : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, logManager) + public MovieDbEpisodeProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory) + : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory) { } public async Task> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken) diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs index 4d7cec79f..facf5cadf 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs @@ -1,7 +1,7 @@ using MediaBrowser.Model.IO; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Movies; using System; @@ -26,14 +26,14 @@ namespace MediaBrowser.Providers.TV private readonly ILocalizationManager _localization; private readonly ILogger _logger; - public MovieDbProviderBase(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILogManager logManager) + public MovieDbProviderBase(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory) { _httpClient = httpClient; _configurationManager = configurationManager; _jsonSerializer = jsonSerializer; _fileSystem = fileSystem; _localization = localization; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); } protected ILogger Logger diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs index 63484483f..217dab663 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; @@ -32,14 +32,14 @@ namespace MediaBrowser.Providers.TV private readonly ILocalizationManager _localization; private readonly ILogger _logger; - public MovieDbSeasonProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, ILogManager logManager) + public MovieDbSeasonProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory) { _httpClient = httpClient; _configurationManager = configurationManager; _fileSystem = fileSystem; _localization = localization; _jsonSerializer = jsonSerializer; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); } public async Task> GetMetadata(SeasonInfo info, CancellationToken cancellationToken) @@ -97,7 +97,7 @@ namespace MediaBrowser.Providers.TV } catch (HttpException ex) { - _logger.Error("No metadata found for {0}", seasonNumber.Value); + _logger.LogError(ex, "No metadata found for {0}", seasonNumber.Value); if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound) { diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs index 6e9b9b239..c3981ae8f 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Movies; @@ -236,7 +236,7 @@ namespace MediaBrowser.Providers.TV if (seriesInfo.networks != null) { - series.Studios = seriesInfo.networks.Select(i => i.name).ToArray(seriesInfo.networks.Count); + series.Studios = seriesInfo.networks.Select(i => i.name).ToArray(); } if (seriesInfo.genres != null) @@ -412,7 +412,7 @@ namespace MediaBrowser.Providers.TV !string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase)) { - _logger.Info("MovieDbSeriesProvider couldn't find meta for language " + language + ". Trying English..."); + _logger.LogInformation("MovieDbSeriesProvider couldn't find meta for language " + language + ". Trying English..."); url = string.Format(GetTvInfo3, id, MovieDbProvider.ApiKey) + "&language=en"; diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs index 41155aca1..d1d8e32c2 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -131,7 +131,7 @@ namespace MediaBrowser.Providers.TV } else { - _logger.Debug("No series identity found for {0}", searchInfo.Name); + _logger.LogDebug("No series identity found for {0}", searchInfo.Name); } return result; diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs index 2839cb434..8bab59595 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using System; using System.Collections.Generic; @@ -358,7 +358,7 @@ namespace MediaBrowser.Providers.TV } catch (HttpException ex) { - _logger.ErrorException("Error updating tvdb series id {0}, language {1}", ex, seriesId, language); + _logger.LogError(ex, "Error updating tvdb series id {ID}, language {Language}", seriesId, language); // Already logged at lower levels, but don't fail the whole operation, unless timed out // We have to fail this to make it run again otherwise new episode data could potentially be missing @@ -389,7 +389,7 @@ namespace MediaBrowser.Providers.TV /// Task. private Task UpdateSeries(string id, string seriesDataPath, long? lastTvDbUpdateTime, string preferredMetadataLanguage, CancellationToken cancellationToken) { - _logger.Info("Updating series from tvdb " + id + ", language " + preferredMetadataLanguage); + _logger.LogInformation("Updating series from tvdb " + id + ", language " + preferredMetadataLanguage); seriesDataPath = Path.Combine(seriesDataPath, id); diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs index 8b7efc28b..515f58c27 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; using System; diff --git a/MediaBrowser.Providers/Users/UserMetadataService.cs b/MediaBrowser.Providers/Users/UserMetadataService.cs index 694315c18..361d42f50 100644 --- a/MediaBrowser.Providers/Users/UserMetadataService.cs +++ b/MediaBrowser.Providers/Users/UserMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Videos/VideoMetadataService.cs b/MediaBrowser.Providers/Videos/VideoMetadataService.cs index f493eb31f..b9868cea9 100644 --- a/MediaBrowser.Providers/Videos/VideoMetadataService.cs +++ b/MediaBrowser.Providers/Videos/VideoMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/Years/YearMetadataService.cs b/MediaBrowser.Providers/Years/YearMetadataService.cs index 783833656..d62cb10b5 100644 --- a/MediaBrowser.Providers/Years/YearMetadataService.cs +++ b/MediaBrowser.Providers/Years/YearMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Server.Mono/EmbyServer.csproj b/MediaBrowser.Server.Mono/EmbyServer.csproj index 480b422bc..609af9674 100644 --- a/MediaBrowser.Server.Mono/EmbyServer.csproj +++ b/MediaBrowser.Server.Mono/EmbyServer.csproj @@ -17,7 +17,14 @@ + + + + + + + @@ -48,6 +55,10 @@ + + + + diff --git a/MediaBrowser.Server.Mono/ImageEncoderHelper.cs b/MediaBrowser.Server.Mono/ImageEncoderHelper.cs index 49955ad65..29760ec55 100644 --- a/MediaBrowser.Server.Mono/ImageEncoderHelper.cs +++ b/MediaBrowser.Server.Mono/ImageEncoderHelper.cs @@ -6,7 +6,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using Emby.Drawing.Skia; using MediaBrowser.Model.System; using MediaBrowser.Model.Globalization; @@ -16,7 +16,6 @@ namespace MediaBrowser.Server.Startup.Common public class ImageEncoderHelper { public static IImageEncoder GetImageEncoder(ILogger logger, - ILogManager logManager, IFileSystem fileSystem, StartupOptions startupOptions, Func httpClient, @@ -28,20 +27,20 @@ namespace MediaBrowser.Server.Startup.Common { try { - return new SkiaEncoder(logManager.GetLogger("Skia"), appPaths, httpClient, fileSystem, localizationManager); + return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager); } catch (Exception ex) { - logger.Info("Skia not available. Will try next image processor. {0}", ex.Message); + logger.LogInformation("Skia not available. Will try next image processor. {0}", ex.Message); } try { - return new ImageMagickEncoder(logManager.GetLogger("ImageMagick"), appPaths, httpClient, fileSystem, environment); + return new ImageMagickEncoder(logger, appPaths, httpClient, fileSystem, environment); } catch { - logger.Info("ImageMagick not available. Will try next image processor."); + logger.LogInformation("ImageMagick not available. Will try next image processor."); } } diff --git a/MediaBrowser.Server.Mono/MonoAppHost.cs b/MediaBrowser.Server.Mono/MonoAppHost.cs index 576eb5c68..c2ec423f8 100644 --- a/MediaBrowser.Server.Mono/MonoAppHost.cs +++ b/MediaBrowser.Server.Mono/MonoAppHost.cs @@ -13,7 +13,7 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Sync; using IsoMounter; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; @@ -21,7 +21,8 @@ namespace MediaBrowser.Server.Mono { public class MonoAppHost : ApplicationHost { - public MonoAppHost(ServerApplicationPaths applicationPaths, ILogManager logManager, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, string releaseAssetFilename, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager) : base(applicationPaths, logManager, options, fileSystem, powerManagement, releaseAssetFilename, environmentInfo, imageEncoder, systemEvents, networkManager) + public MonoAppHost(ServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, string releaseAssetFilename, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager) + : base(applicationPaths, loggerFactory, options, fileSystem, powerManagement, releaseAssetFilename, environmentInfo, imageEncoder, systemEvents, networkManager) { } @@ -86,7 +87,8 @@ namespace MediaBrowser.Server.Mono protected override IHttpListener CreateHttpListener() { - return new EmbyServer.SocketSharp.WebSocketSharpListener(LogManager.GetLogger("HttpServer"), + return new EmbyServer.SocketSharp.WebSocketSharpListener( + Logger, Certificate, StreamHelper, TextEncoding, diff --git a/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs b/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs index 2fd95ab82..2499d8bb5 100644 --- a/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs +++ b/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs @@ -1,5 +1,5 @@ using Emby.Server.Implementations.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using Mono.Unix.Native; @@ -15,7 +15,7 @@ namespace MediaBrowser.Server.Mono.Native public override void SetExecutable(string path) { // Linux: File permission to 666, and user's execute bit - Logger.Info("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path); + Logger.LogInformation("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path); Syscall.chmod(path, FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH); } diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 887a9545f..f512fc98e 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -1,4 +1,3 @@ -using MediaBrowser.Model.Logging; using MediaBrowser.Server.Mono.Native; using MediaBrowser.Server.Startup.Common; using System; @@ -15,16 +14,19 @@ using Emby.Drawing; using Emby.Server.Implementations; using Emby.Server.Implementations.EnvironmentInfo; using Emby.Server.Implementations.IO; -using Emby.Server.Implementations.Logging; using Emby.Server.Implementations.Networking; using MediaBrowser.Controller; using MediaBrowser.Model.IO; using MediaBrowser.Model.System; using Mono.Unix.Native; -using ILogger = MediaBrowser.Model.Logging.ILogger; using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate; using System.Threading; using InteropServices = System.Runtime.InteropServices; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using ILogger = Microsoft.Extensions.Logging.ILogger; +using Serilog; +using Serilog.AspNetCore; namespace MediaBrowser.Server.Mono { @@ -33,7 +35,7 @@ namespace MediaBrowser.Server.Mono private static ILogger _logger; private static IFileSystem FileSystem; private static IServerApplicationPaths _appPaths; - private static ILogManager _logManager; + private static ILoggerFactory _loggerFactory; private static readonly TaskCompletionSource ApplicationTaskCompletionSource = new TaskCompletionSource(); private static bool _restartOnShutdown; @@ -52,23 +54,21 @@ namespace MediaBrowser.Server.Mono var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath); _appPaths = appPaths; - using (var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server")) + createLogger(); + + using (var loggerFactory = new SerilogLoggerFactory()) { - _logManager = logManager; + _loggerFactory = loggerFactory; - var task = logManager.ReloadLogger(LogSeverity.Debug, CancellationToken.None); - Task.WaitAll(task); - logManager.AddConsoleOutput(); + _logger = loggerFactory.CreateLogger("Main"); - var logger = _logger = logManager.GetLogger("Main"); - - ApplicationHost.LogEnvironmentInfo(logger, appPaths, true); + ApplicationHost.LogEnvironmentInfo(_logger, appPaths, true); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - RunApplication(appPaths, logManager, options); + RunApplication(appPaths, loggerFactory, options); - _logger.Info("Disposing app host"); + _logger.LogInformation("Disposing app host"); if (_restartOnShutdown) { @@ -109,27 +109,27 @@ namespace MediaBrowser.Server.Mono return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath); } - private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options) + private static void RunApplication(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory, StartupOptions options) { // Allow all https requests ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); var environmentInfo = GetEnvironmentInfo(); - var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true); + var fileSystem = new ManagedFileSystem(loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true); FileSystem = fileSystem; using (var appHost = new MonoAppHost(appPaths, - logManager, + loggerFactory, options, fileSystem, new PowerManagement(), "embyserver-mono_{version}.zip", environmentInfo, new NullImageEncoder(), - new SystemEvents(logManager.GetLogger("SystemEvents")), - new NetworkManager(logManager.GetLogger("NetworkManager"), environmentInfo))) + new SystemEvents(loggerFactory.CreateLogger("SystemEvents")), + new NetworkManager(loggerFactory.CreateLogger("NetworkManager"), environmentInfo))) { if (options.ContainsOption("-v")) { @@ -137,13 +137,14 @@ namespace MediaBrowser.Server.Mono return; } - Console.WriteLine("appHost.Init"); + //Console.WriteLine("appHost.Init"); appHost.Init(); - appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); + appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); - Console.WriteLine("Running startup tasks"); + //Console.WriteLine("Running startup tasks"); + _logger.LogInformation("Running startup tasks"); var task = appHost.RunStartupTasks(); Task.WaitAll(task); @@ -154,6 +155,54 @@ namespace MediaBrowser.Server.Mono } } + private static void createLogger() + { + var logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR"); + if (string.IsNullOrEmpty(logDir)){ + logDir = Path.Combine(_appPaths.ProgramDataPath, "logs"); + Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir); + } + try + { + string path = Path.Combine(_appPaths.ConfigurationDirectoryPath, "logging.json"); + + if (!File.Exists(path)) + { + var assembly = typeof(MainClass).Assembly; + // For some reason the csproj name is used instead of the assembly name + var resourcePath = "EmbyServer.Resources.Configuration.logging.json"; + using (Stream rscstr = assembly.GetManifestResourceStream(resourcePath)) + using (Stream fstr = File.Open(path, FileMode.CreateNew)) + { + rscstr.CopyTo(fstr); + } + } + var configuration = new ConfigurationBuilder() + .SetBasePath(_appPaths.ConfigurationDirectoryPath) + .AddJsonFile("logging.json") + .AddEnvironmentVariables("JELLYFIN_") + .Build(); + + Serilog.Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .Enrich.FromLogContext() + .CreateLogger(); + } + catch (Exception ex) + { + Serilog.Log.Logger = new LoggerConfiguration() + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.File( + Path.Combine(logDir, "log_.log"), + rollingInterval: RollingInterval.Day, + outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}") + .Enrich.FromLogContext() + .CreateLogger(); + + Serilog.Log.Logger.Fatal(ex, "Failed to read logger config"); + } + } + private static MonoEnvironmentInfo GetEnvironmentInfo() { var info = new MonoEnvironmentInfo(); @@ -221,7 +270,7 @@ namespace MediaBrowser.Server.Mono } catch (Exception ex) { - _logger.ErrorException("Error getting unix name", ex); + _logger.LogError(ex, "Error getting unix name"); } _unixName = uname; } @@ -243,8 +292,12 @@ namespace MediaBrowser.Server.Mono { var exception = (Exception)e.ExceptionObject; - new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception); + //new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception); + _logger.LogCritical(exception, "Unhandled Exception"); + + // TODO: @bond + /* if (!Debugger.IsAttached) { var message = LogHelper.GetLogMessage(exception).ToString(); @@ -255,6 +308,7 @@ namespace MediaBrowser.Server.Mono Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception)); } } + */ } public static void Shutdown() @@ -271,7 +325,7 @@ namespace MediaBrowser.Server.Mono private static void StartNewInstance(StartupOptions startupOptions) { - _logger.Info("Starting new instance"); + _logger.LogInformation("Starting new instance"); string module = startupOptions.GetOption("-restartpath"); string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty; @@ -290,8 +344,8 @@ namespace MediaBrowser.Server.Mono commandLineArgsString = string.Join(" ", args); } - _logger.Info("Executable: {0}", module); - _logger.Info("Arguments: {0}", commandLineArgsString); + _logger.LogInformation("Executable: {0}", module); + _logger.LogInformation("Arguments: {0}", commandLineArgsString); Process.Start(module, commandLineArgsString); } diff --git a/MediaBrowser.Server.Mono/Resources/Configuration/logging.json b/MediaBrowser.Server.Mono/Resources/Configuration/logging.json new file mode 100644 index 000000000..78f99b2ad --- /dev/null +++ b/MediaBrowser.Server.Mono/Resources/Configuration/logging.json @@ -0,0 +1,19 @@ +{ + "Serilog": { + "MinimumLevel": "Information", + "WriteTo": [ + { "Name": "Console", + "Args": { + "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}" + } + }, + { "Name": "File", + "Args": { + "path": "%JELLYFIN_LOG_DIR%//log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}" + } + } + ] + } +} diff --git a/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs b/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs index 6c2dd0f76..fd32640a2 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs @@ -1,5 +1,5 @@ using MediaBrowser.Common.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; @@ -55,7 +55,7 @@ namespace EmbyServer.SocketSharp void socket_OnError(object sender, SocketHttpListener.ErrorEventArgs e) { - _logger.Error("Error in SharpWebSocket: {0}", e.Message ?? string.Empty); + _logger.LogError("Error in SharpWebSocket: {0}", e.Message ?? string.Empty); //EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger); } diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs index e75a38e38..993863e8c 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using SocketHttpListener.Net; using System; using System.Collections.Generic; @@ -74,7 +74,7 @@ namespace EmbyServer.SocketSharp foreach (var prefix in urlPrefixes) { - _logger.Info("Adding HttpListener prefix " + prefix); + _logger.LogInformation("Adding HttpListener prefix " + prefix); _listener.Prefixes.Add(prefix); } @@ -93,7 +93,7 @@ namespace EmbyServer.SocketSharp { var url = request.Url.ToString(); - logger.Info("{0} {1}. UserAgent: {2}", request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod, url, request.UserAgent ?? string.Empty); + logger.LogInformation("{0} {1}. UserAgent: {2}", request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod, url, request.UserAgent ?? string.Empty); } private Task InitTask(HttpListenerContext context, CancellationToken cancellationToken) @@ -114,7 +114,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.ErrorException("Error processing request", ex); + _logger.LogError(ex, "Error processing request"); httpReq = httpReq ?? GetRequest(context); return ErrorHandler(ex, httpReq, true, true); @@ -148,7 +148,7 @@ namespace EmbyServer.SocketSharp if (connectingArgs.AllowConnection) { - _logger.Debug("Web socket connection allowed"); + _logger.LogDebug("Web socket connection allowed"); var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false); @@ -169,14 +169,14 @@ namespace EmbyServer.SocketSharp } else { - _logger.Warn("Web socket connection not allowed"); + _logger.LogWarning("Web socket connection not allowed"); ctx.Response.StatusCode = 401; ctx.Response.Close(); } } catch (Exception ex) { - _logger.ErrorException("AcceptWebSocketAsync error", ex); + _logger.LogError(ex, "AcceptWebSocketAsync error"); ctx.Response.StatusCode = 500; ctx.Response.Close(); } @@ -206,7 +206,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.ErrorException("Error closing web socket response", ex); + _logger.LogError(ex, "Error closing web socket response"); } } @@ -259,4 +259,4 @@ namespace EmbyServer.SocketSharp } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs index 84e37a58c..1e1c3db7c 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs @@ -4,7 +4,7 @@ using System.IO; using System.Text; using Emby.Server.Implementations.HttpServer; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using SocketHttpListener.Net; using IHttpFile = MediaBrowser.Model.Services.IHttpFile; diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs index 15ff6675d..08fa4cbd6 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs @@ -6,7 +6,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using HttpListenerResponse = SocketHttpListener.Net.HttpListenerResponse; using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse; @@ -112,7 +112,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.ErrorException("Error in HttpListenerResponseWrapper: " + ex.Message, ex); + _logger.LogError(ex, "Error in HttpListenerResponseWrapper"); } } } diff --git a/MediaBrowser.Tests/M3uParserTest.cs b/MediaBrowser.Tests/M3uParserTest.cs index 1b42a3823..b5b25b53d 100644 --- a/MediaBrowser.Tests/M3uParserTest.cs +++ b/MediaBrowser.Tests/M3uParserTest.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using Emby.Server.Implementations.Cryptography; using Emby.Server.Implementations.LiveTv.TunerHosts; using MediaBrowser.Common.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MediaBrowser.Tests diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs b/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs index 8acc490e7..f99103438 100644 --- a/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs +++ b/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs @@ -2,7 +2,7 @@ using System.IO; using System.Threading; using Emby.Server.MediaEncoding.Subtitles; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -111,4 +111,4 @@ namespace MediaBrowser.Tests.MediaEncoding.Subtitles } } -} \ No newline at end of file +} diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index f0c352157..58d02ef04 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; @@ -245,7 +245,7 @@ namespace MediaBrowser.WebDashboard.Api } catch (Exception ex) { - _logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name); + _logger.LogError(ex, "Error getting plugin information from {Plugin}", p.GetType().Name); return null; } }) diff --git a/MediaBrowser.WebDashboard/Api/PackageCreator.cs b/MediaBrowser.WebDashboard/Api/PackageCreator.cs index 619d0660f..f510ed51f 100644 --- a/MediaBrowser.WebDashboard/Api/PackageCreator.cs +++ b/MediaBrowser.WebDashboard/Api/PackageCreator.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Configuration; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs index e4b11a6fc..dac3f4967 100644 --- a/MediaBrowser.XbmcMetadata/EntryPoint.cs +++ b/MediaBrowser.XbmcMetadata/EntryPoint.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using MediaBrowser.XbmcMetadata.Savers; using System; @@ -72,7 +72,7 @@ namespace MediaBrowser.XbmcMetadata } catch (Exception ex) { - _logger.ErrorException("Error saving metadata for {0}", ex, item.Path ?? item.Name); + _logger.LogError(ex, "Error saving metadata for {path}", item.Path ?? item.Name); } } } diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 3b8d68776..0aaa0b362 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using MediaBrowser.XbmcMetadata.Savers; using System; @@ -294,7 +294,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } else { - Logger.Warn("Invalid Added value found: " + val); + Logger.LogWarning("Invalid Added value found: " + val); } } break; diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index ce7b924eb..ce56e080a 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; diff --git a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs index 94b4c30f2..e6b4eea1c 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Xml; using MediaBrowser.Model.IO; using MediaBrowser.Model.Xml; @@ -81,7 +81,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } catch (Exception ex) { - Logger.ErrorException("Error parsing set node", ex); + Logger.LogError(ex, "Error parsing set node"); } } } diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs index ef1b8ebb2..bcb70ee45 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Globalization; using System.Xml; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs index 570a7fed8..3b46ff7d6 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Xml; using MediaBrowser.Model.IO; @@ -91,7 +91,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } else { - Logger.Info("Unrecognized series status: " + status); + Logger.LogInformation("Unrecognized series status: " + status); } } diff --git a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs index f56ceed89..e8028f6ad 100644 --- a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.IO; using System.Threading; diff --git a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs index 4fcc222f8..b6b61258b 100644 --- a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.IO; using System.Threading; diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs index eeb55d8bc..c7ff55323 100644 --- a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using MediaBrowser.XbmcMetadata.Savers; using System.Linq; @@ -54,4 +54,4 @@ namespace MediaBrowser.XbmcMetadata.Providers .FirstOrDefault(i => i != null); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs index 3bc10f35b..6883048f6 100644 --- a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.Collections.Generic; using System.IO; diff --git a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs index 031bdc8d2..1e4ccbe38 100644 --- a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.XbmcMetadata.Providers @@ -30,4 +30,4 @@ namespace MediaBrowser.XbmcMetadata.Providers { } } -} \ No newline at end of file +} diff --git a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs index 0d214f58d..ddd32512a 100644 --- a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.IO; using System.Threading; diff --git a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs index 368d37e0a..34a7a088e 100644 --- a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.IO; using System.Threading; diff --git a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs index dcce00d69..54d0b8bae 100644 --- a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; diff --git a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs index f571dc2b7..cc0da1b36 100644 --- a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using System.Collections.Generic; using System.Globalization; @@ -91,4 +91,4 @@ namespace MediaBrowser.XbmcMetadata.Savers { } } -} \ No newline at end of file +} diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index f6ea9b4b2..2b550193f 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using System; using System.Collections.Generic; @@ -230,7 +230,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } catch (Exception ex) { - Logger.Error("Error setting hidden attribute on {0} - {1}", path, ex.Message); + Logger.LogError(ex, "Error setting hidden attribute on {path}", path); } } @@ -283,7 +283,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } catch (XmlException ex) { - Logger.ErrorException("Error reading existng nfo", ex); + Logger.LogError(ex, "Error reading existing nfo"); } writer.WriteEndElement(); @@ -353,7 +353,8 @@ namespace MediaBrowser.XbmcMetadata.Savers if (!string.IsNullOrEmpty(stream.Language)) { - // https://emby.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify + // http://web.archive.org/web/20181230211547/https://emby.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify + // Web Archive version of link since it's not really explained in the thread. writer.WriteElementString("language", RemoveInvalidXMLChars(stream.Language)); } @@ -774,9 +775,9 @@ namespace MediaBrowser.XbmcMetadata.Savers try { var tagName = GetTagForProviderKey(providerKey); - //Logger.Debug("Verifying custom provider tagname {0}", tagName); + //logger.LogDebug("Verifying custom provider tagname {0}", tagName); XmlConvert.VerifyName(tagName); - //Logger.Debug("Saving custom provider tagname {0}", tagName); + //logger.LogDebug("Saving custom provider tagname {0}", tagName); writer.WriteElementString(GetTagForProviderKey(providerKey), providerId); } @@ -1000,7 +1001,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } catch (Exception ex) { - logger.ErrorException("Error reading existing xml tags from {0}.", ex, path); + logger.LogError(ex, "Error reading existing xml tags from {path}.", path); return; } diff --git a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs index 33f96fc8f..d1f30b1fe 100644 --- a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using System.Collections.Generic; using System.Globalization; @@ -115,4 +115,4 @@ namespace MediaBrowser.XbmcMetadata.Savers { } } -} \ No newline at end of file +} diff --git a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs index 0fc74e66b..c703a9ea6 100644 --- a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.IO; using System.Xml; diff --git a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs index 5a626eef9..50ae8d24e 100644 --- a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Globalization; using System.IO; diff --git a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs index 27bc5f038..e0f08dbdb 100644 --- a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Globalization; using System.IO; diff --git a/Mono.Nat/NatManager.cs b/Mono.Nat/NatManager.cs index 752fd0416..3ed01a6b3 100644 --- a/Mono.Nat/NatManager.cs +++ b/Mono.Nat/NatManager.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Linq; namespace Mono.Nat diff --git a/Mono.Nat/Pmp/PmpNatDevice.cs b/Mono.Nat/Pmp/PmpNatDevice.cs index bf27bfebc..fbf3032d4 100644 --- a/Mono.Nat/Pmp/PmpNatDevice.cs +++ b/Mono.Nat/Pmp/PmpNatDevice.cs @@ -32,7 +32,7 @@ using System.Threading; using System.Collections.Generic; using System.Threading.Tasks; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Mono.Nat.Pmp { @@ -95,7 +95,7 @@ namespace Mono.Nat.Pmp try { - byte[] buffer = package.ToArray(package.Count); + byte[] buffer = package.ToArray(); int attempt = 0; int delay = PmpConstants.RetryDelay; @@ -132,7 +132,7 @@ namespace Mono.Nat.Pmp mapping.Protocol, mapping.PrivatePort, e.Message); - _logger.Debug(message); + _logger.LogDebug(message); throw e; } @@ -183,7 +183,7 @@ namespace Mono.Nat.Pmp }; var errorMsg = errors[resultCode]; - _logger.Debug("Error in CreatePortMapListen: " + errorMsg); + _logger.LogDebug("Error in CreatePortMapListen: " + errorMsg); return; } @@ -198,7 +198,7 @@ namespace Mono.Nat.Pmp } catch (Exception ex) { - _logger.ErrorException("Error in CreatePortMapListen", ex); + _logger.LogError(ex, "Error in CreatePortMapListen"); return; } } diff --git a/Mono.Nat/Pmp/PmpSearcher.cs b/Mono.Nat/Pmp/PmpSearcher.cs index 180fb48d7..98cf37f14 100644 --- a/Mono.Nat/Pmp/PmpSearcher.cs +++ b/Mono.Nat/Pmp/PmpSearcher.cs @@ -37,7 +37,7 @@ using Mono.Nat.Pmp; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading.Tasks; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Linq; namespace Mono.Nat @@ -208,7 +208,7 @@ namespace Mono.Nat return; int errorcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, 2)); if (errorcode != 0) - _logger.Debug("Non zero error: {0}", errorcode); + _logger.LogDebug("Non zero error: {0}", errorcode); IPAddress publicIp = new IPAddress(new byte[] { response[8], response[9], response[10], response[11] }); nextSearch = DateTime.Now.AddMinutes(5); diff --git a/Mono.Nat/Upnp/Messages/GetServicesMessage.cs b/Mono.Nat/Upnp/Messages/GetServicesMessage.cs index 3395b7596..4b765fd42 100644 --- a/Mono.Nat/Upnp/Messages/GetServicesMessage.cs +++ b/Mono.Nat/Upnp/Messages/GetServicesMessage.cs @@ -28,7 +28,7 @@ using System; using System.Diagnostics; using System.Net; using MediaBrowser.Common.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Mono.Nat.Upnp { @@ -42,10 +42,10 @@ namespace Mono.Nat.Upnp : base(null) { if (string.IsNullOrEmpty(description)) - _logger.Warn("Description is null"); + _logger.LogWarning("Description is null"); if (hostAddress == null) - _logger.Warn("hostaddress is null"); + _logger.LogWarning("hostaddress is null"); this.servicesDescriptionUrl = description; this.hostAddress = hostAddress; diff --git a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs index 7c1e89d3b..bcf358d1c 100644 --- a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs +++ b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs @@ -37,7 +37,7 @@ using System.Diagnostics; using System.Net.Sockets; using System.Net.NetworkInformation; using MediaBrowser.Common.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Dlna; using System.Threading.Tasks; @@ -90,7 +90,7 @@ namespace Mono.Nat } catch (Exception ex) { - _logger.ErrorException("Error decoding device response", ex); + _logger.LogError(ex, "Error decoding device response"); } } diff --git a/Mono.Nat/Upnp/UpnpNatDevice.cs b/Mono.Nat/Upnp/UpnpNatDevice.cs index cae7f5fc8..62539103a 100644 --- a/Mono.Nat/Upnp/UpnpNatDevice.cs +++ b/Mono.Nat/Upnp/UpnpNatDevice.cs @@ -34,7 +34,7 @@ using System.Text; using System.Diagnostics; using System.Threading.Tasks; using MediaBrowser.Common.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Dlna; namespace Mono.Nat.Upnp @@ -77,7 +77,7 @@ namespace Mono.Nat.Upnp // Are we going to get addresses with the "http://" attached? if (locationDetails.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { - _logger.Debug("Found device at: {0}", locationDetails); + _logger.LogDebug("Found device at: {0}", locationDetails); // This bit strings out the "http://" from the string locationDetails = locationDetails.Substring(7); @@ -89,7 +89,7 @@ namespace Mono.Nat.Upnp } else { - _logger.Debug("Couldn't decode address. Please send following string to the developer: "); + _logger.LogDebug("Couldn't decode address. Please send following string to the developer: "); } } @@ -116,7 +116,7 @@ namespace Mono.Nat.Upnp { if (response.StatusCode != HttpStatusCode.OK) { - _logger.Debug("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode); + _logger.LogDebug("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode); return; // FIXME: This the best thing to do?? } @@ -139,7 +139,7 @@ namespace Mono.Nat.Upnp { return; } - _logger.Debug("{0}: Couldn't parse services list", HostEndPoint); + _logger.LogDebug("{0}: Couldn't parse services list", HostEndPoint); System.Threading.Thread.Sleep(10); } } @@ -155,14 +155,14 @@ namespace Mono.Nat.Upnp { //If the service is a WANIPConnection, then we have what we want string type = service["serviceType"].InnerText; - _logger.Debug("{0}: Found service: {1}", HostEndPoint, type); + _logger.LogDebug("{0}: Found service: {1}", HostEndPoint, type); // TODO: Add support for version 2 of UPnP. if (string.Equals(type, "urn:schemas-upnp-org:service:WANPPPConnection:1", StringComparison.OrdinalIgnoreCase) || string.Equals(type, "urn:schemas-upnp-org:service:WANIPConnection:1", StringComparison.OrdinalIgnoreCase)) { this.controlUrl = service["controlURL"].InnerText; - _logger.Debug("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl); + _logger.LogDebug("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl); Uri u; if (Uri.TryCreate(controlUrl, UriKind.RelativeOrAbsolute, out u)) @@ -174,15 +174,15 @@ namespace Mono.Nat.Upnp if (IPAddress.TryParse(u.Host, out parsedHostIpAddress)) { this.hostEndPoint = new IPEndPoint(parsedHostIpAddress, u.Port); - //_logger.Debug("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint); + //_logger.LogDebug("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint); this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length); - //_logger.Debug("{0}: New control url: {1}", HostEndPoint, controlUrl); + //_logger.LogDebug("{0}: New control url: {1}", HostEndPoint, controlUrl); } } } else { - _logger.Debug("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl); + _logger.LogDebug("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl); } return; } @@ -266,4 +266,4 @@ namespace Mono.Nat.Upnp this.hostEndPoint, "Manually Check" /*this.GetExternalIP()*/, this.controlUrl, this.serviceDescriptionUrl, this.serviceType, this.LastSeen); } } -} \ No newline at end of file +} diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index bc8594649..65ec0ca71 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -7,7 +7,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; namespace Rssdp.Infrastructure @@ -131,7 +131,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.ErrorException("Error in BeginListeningForBroadcasts", ex); + _logger.LogError(ex, "Error in BeginListeningForBroadcasts"); } } } @@ -148,7 +148,7 @@ namespace Rssdp.Infrastructure { if (_BroadcastListenSocket != null) { - _logger.Info("{0} disposing _BroadcastListenSocket.", GetType().Name); + _logger.LogInformation("{0} disposing _BroadcastListenSocket.", GetType().Name); _BroadcastListenSocket.Dispose(); _BroadcastListenSocket = null; } @@ -197,7 +197,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.ErrorException("Error sending socket message from {0} to {1}", ex, socket.LocalIPAddress.ToString(), destination.ToString()); + _logger.LogError(ex, "Error sending socket message from {0} to {1}", socket.LocalIPAddress.ToString(), destination.ToString()); } } @@ -282,11 +282,11 @@ namespace Rssdp.Infrastructure var sockets = _sendSockets.ToList(); _sendSockets = null; - _logger.Info("{0} Disposing {1} sendSockets", GetType().Name, sockets.Count); + _logger.LogInformation("{0} Disposing {1} sendSockets", GetType().Name, sockets.Count); foreach (var socket in sockets) { - _logger.Info("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress); + _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress); socket.Dispose(); } } @@ -376,7 +376,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.ErrorException("Error in CreateSsdpUdpSocket. IPAddress: {0}", ex, address); + _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", address); } } } @@ -508,4 +508,4 @@ namespace Rssdp.Infrastructure #endregion } -} \ No newline at end of file +} diff --git a/SocketHttpListener/Net/HttpConnection.cs b/SocketHttpListener/Net/HttpConnection.cs index 9b4fb8705..4fc9a468c 100644 --- a/SocketHttpListener/Net/HttpConnection.cs +++ b/SocketHttpListener/Net/HttpConnection.cs @@ -8,7 +8,7 @@ using System.Text; using System.Threading.Tasks; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using MediaBrowser.Model.Text; @@ -173,7 +173,7 @@ namespace SocketHttpListener.Net private void OnTimeout(object unused) { - //_logger.Info("HttpConnection timer fired"); + //_logger.LogInformation("HttpConnection timer fired"); CloseSocket(); Unbind(); } @@ -556,4 +556,4 @@ namespace SocketHttpListener.Net } } } -} \ No newline at end of file +} diff --git a/SocketHttpListener/Net/HttpEndPointListener.cs b/SocketHttpListener/Net/HttpEndPointListener.cs index 254e76140..fb093314c 100644 --- a/SocketHttpListener/Net/HttpEndPointListener.cs +++ b/SocketHttpListener/Net/HttpEndPointListener.cs @@ -8,7 +8,7 @@ using System.Security.Cryptography.X509Certificates; using System.Threading; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using MediaBrowser.Model.Text; @@ -173,7 +173,7 @@ namespace SocketHttpListener.Net { HttpEndPointListener epl = (HttpEndPointListener)acceptEventArg.UserToken; - epl._logger.ErrorException("Error in socket.AcceptAsync", ex); + epl._logger.LogError(ex, "Error in socket.AcceptAsync"); } } @@ -204,7 +204,7 @@ namespace SocketHttpListener.Net if (socketError == SocketError.ConnectionReset) { - epl._logger.Error("SocketError.ConnectionReset reported. Attempting to re-accept."); + epl._logger.LogError("SocketError.ConnectionReset reported. Attempting to re-accept."); return; } @@ -223,13 +223,13 @@ namespace SocketHttpListener.Net { var remoteEndPointString = accepted.RemoteEndPoint == null ? string.Empty : accepted.RemoteEndPoint.ToString(); var localEndPointString = accepted.LocalEndPoint == null ? string.Empty : accepted.LocalEndPoint.ToString(); - //_logger.Info("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure); + //_logger.LogInformation("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure); HttpConnection conn = new HttpConnection(epl._logger, accepted, epl, epl._secure, epl._cert, epl._cryptoProvider, epl._streamHelper, epl._textEncoding, epl._fileSystem, epl._environment); await conn.Init().ConfigureAwait(false); - //_logger.Debug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId); + //_logger.LogDebug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId); lock (epl._unregisteredConnections) { epl._unregisteredConnections[conn] = conn; @@ -238,7 +238,7 @@ namespace SocketHttpListener.Net } catch (Exception ex) { - epl._logger.ErrorException("Error in ProcessAccept", ex); + epl._logger.LogError(ex, "Error in ProcessAccept"); TryClose(accepted); epl.Accept(); diff --git a/SocketHttpListener/Net/HttpEndPointManager.cs b/SocketHttpListener/Net/HttpEndPointManager.cs index 45af92c01..01b5ae9bd 100644 --- a/SocketHttpListener/Net/HttpEndPointManager.cs +++ b/SocketHttpListener/Net/HttpEndPointManager.cs @@ -6,7 +6,7 @@ using System.Net.Sockets; using System.Reflection; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using SocketHttpListener.Primitives; diff --git a/SocketHttpListener/Net/HttpListener.cs b/SocketHttpListener/Net/HttpListener.cs index 759be64c9..941b99f35 100644 --- a/SocketHttpListener/Net/HttpListener.cs +++ b/SocketHttpListener/Net/HttpListener.cs @@ -7,7 +7,7 @@ using System.Security.Cryptography.X509Certificates; using MediaBrowser.Common.Net; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using MediaBrowser.Model.Text; @@ -58,11 +58,6 @@ namespace SocketHttpListener.Net auth_schemes = AuthenticationSchemes.Anonymous; } - public HttpListener(X509Certificate certificate, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, INetworkManager networkManager, ITextEncoding textEncoding, IStreamHelper streamHelper, IFileSystem fileSystem, IEnvironmentInfo environmentInfo) - :this(new NullLogger(), certificate, cryptoProvider, socketFactory, networkManager, textEncoding, streamHelper, fileSystem, environmentInfo) - { - } - public HttpListener(ILogger logger, X509Certificate certificate, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, INetworkManager networkManager, ITextEncoding textEncoding, IStreamHelper streamHelper, IFileSystem fileSystem, IEnvironmentInfo environmentInfo) : this(logger, cryptoProvider, socketFactory, networkManager, textEncoding, streamHelper, fileSystem, environmentInfo) { diff --git a/SocketHttpListener/Net/HttpListenerContext.cs b/SocketHttpListener/Net/HttpListenerContext.cs index b90f07567..0aaac1ad5 100644 --- a/SocketHttpListener/Net/HttpListenerContext.cs +++ b/SocketHttpListener/Net/HttpListenerContext.cs @@ -1,6 +1,10 @@ using System; using System.Net; using System.Security.Principal; +using MediaBrowser.Model.Cryptography; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; +using MediaBrowser.Model.Text; using SocketHttpListener.Net.WebSockets; using System.Threading.Tasks; diff --git a/SocketHttpListener/Net/HttpListenerPrefixCollection.cs b/SocketHttpListener/Net/HttpListenerPrefixCollection.cs index 53efcb0fa..ed99af1a6 100644 --- a/SocketHttpListener/Net/HttpListenerPrefixCollection.cs +++ b/SocketHttpListener/Net/HttpListenerPrefixCollection.cs @@ -1,7 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace SocketHttpListener.Net { diff --git a/SocketHttpListener/Net/HttpResponseStream.Managed.cs b/SocketHttpListener/Net/HttpResponseStream.Managed.cs index 1a8a195fb..e727f1b4a 100644 --- a/SocketHttpListener/Net/HttpResponseStream.Managed.cs +++ b/SocketHttpListener/Net/HttpResponseStream.Managed.cs @@ -8,7 +8,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; namespace SocketHttpListener.Net diff --git a/debian/changelog b/debian/changelog index e4176123d..9dc21d467 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,10 @@ +jellyfin (3.5.2-5) unstable; urgency=medium + + * Fully GPL'd release - remove tainted code from MediaBrowser.Common + * Several code cleanups and tweaks + + -- Joshua Boniface Fri, 28 Dec 2018 10:26:30 -0500 + jellyfin (3.5.2-4) unstable; urgency=medium * Correct manifest.json bug and vdpau diff --git a/debian/jellyfin.service b/debian/jellyfin.service index d5a999cf5..4c3739909 100644 --- a/debian/jellyfin.service +++ b/debian/jellyfin.service @@ -7,8 +7,8 @@ Type = simple EnvironmentFile = /etc/default/jellyfin User = jellyfin ExecStart = /usr/bin/jellyfin -programdata ${JELLYFIN_DATA} -restartpath ${JELLYFIN_RESTART_SCRIPT} ${JELLYFIN_ADD_OPTS} -Restart = on-abort -TimeoutSec = 20 +Restart = on-failure +TimeoutSec = 15 [Install] WantedBy = multi-user.target diff --git a/debian/rules b/debian/rules index 6c915af6f..10a3a8486 100755 --- a/debian/rules +++ b/debian/rules @@ -2,6 +2,7 @@ CONFIG := Release TERM := xterm SHELL := /bin/bash +DOTNETRUNTIME := linux-x64 export DH_VERBOSE=1 export DOTNET_CLI_TELEMETRY_OPTOUT=1 @@ -15,7 +16,7 @@ override_dh_auto_test: override_dh_clistrip: override_dh_auto_build: - dotnet publish --configuration $(CONFIG) --output='$(CURDIR)/usr/lib/jellyfin/bin' --self-contained --runtime linux-x64 + dotnet publish --configuration $(CONFIG) --output='$(CURDIR)/usr/lib/jellyfin/bin' --self-contained --runtime $(DOTNETRUNTIME) override_dh_auto_clean: dotnet clean -maxcpucount:1 --configuration $(CONFIG) || true diff --git a/new-file-header.txt b/new-file-header.txt new file mode 100644 index 000000000..4247a8e24 --- /dev/null +++ b/new-file-header.txt @@ -0,0 +1,22 @@ +### This header should be used to start new files. +### It provides an explicit per-file license reference that should be present on all new files. +### To use this header, delete these lines and the following empty line, modify to +### the proper full path, and then add new code following the header and a single empty line. + +// +// Part of the Jellyfin project (https://jellyfin.media) +// +// All copyright belongs to the Jellyfin contributors; a full list can +// be found in the file CONTRIBUTORS.md +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see .