HttpServer.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. using Funq;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Model.Logging;
  6. using ServiceStack.Api.Swagger;
  7. using ServiceStack.Common.Web;
  8. using ServiceStack.Configuration;
  9. using ServiceStack.Logging;
  10. using ServiceStack.ServiceHost;
  11. using ServiceStack.ServiceInterface.Cors;
  12. using ServiceStack.Text;
  13. using ServiceStack.WebHost.Endpoints;
  14. using ServiceStack.WebHost.Endpoints.Extensions;
  15. using ServiceStack.WebHost.Endpoints.Support;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Net;
  22. using System.Net.WebSockets;
  23. using System.Reactive.Linq;
  24. using System.Reflection;
  25. using System.Text;
  26. using System.Threading.Tasks;
  27. namespace MediaBrowser.Server.Implementations.HttpServer
  28. {
  29. /// <summary>
  30. /// Class HttpServer
  31. /// </summary>
  32. public class HttpServer : HttpListenerBase, IHttpServer
  33. {
  34. /// <summary>
  35. /// The logger
  36. /// </summary>
  37. private readonly ILogger _logger;
  38. /// <summary>
  39. /// Gets the URL prefix.
  40. /// </summary>
  41. /// <value>The URL prefix.</value>
  42. public string UrlPrefix { get; private set; }
  43. /// <summary>
  44. /// The _rest services
  45. /// </summary>
  46. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  47. /// <summary>
  48. /// This subscribes to HttpListener requests and finds the appropriate BaseHandler to process it
  49. /// </summary>
  50. /// <value>The HTTP listener.</value>
  51. private IDisposable HttpListener { get; set; }
  52. /// <summary>
  53. /// Occurs when [web socket connected].
  54. /// </summary>
  55. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  56. /// <summary>
  57. /// Gets the default redirect path.
  58. /// </summary>
  59. /// <value>The default redirect path.</value>
  60. private string DefaultRedirectPath { get; set; }
  61. /// <summary>
  62. /// Gets or sets the name of the server.
  63. /// </summary>
  64. /// <value>The name of the server.</value>
  65. private string ServerName { get; set; }
  66. /// <summary>
  67. /// The _container adapter
  68. /// </summary>
  69. private readonly ContainerAdapter _containerAdapter;
  70. /// <summary>
  71. /// Initializes a new instance of the <see cref="HttpServer" /> class.
  72. /// </summary>
  73. /// <param name="applicationHost">The application host.</param>
  74. /// <param name="logManager">The log manager.</param>
  75. /// <param name="serverName">Name of the server.</param>
  76. /// <param name="defaultRedirectpath">The default redirectpath.</param>
  77. /// <exception cref="System.ArgumentNullException">urlPrefix</exception>
  78. public HttpServer(IApplicationHost applicationHost, ILogManager logManager, string serverName, string defaultRedirectpath)
  79. : base()
  80. {
  81. if (logManager == null)
  82. {
  83. throw new ArgumentNullException("logManager");
  84. }
  85. if (applicationHost == null)
  86. {
  87. throw new ArgumentNullException("applicationHost");
  88. }
  89. if (string.IsNullOrEmpty(serverName))
  90. {
  91. throw new ArgumentNullException("serverName");
  92. }
  93. if (string.IsNullOrEmpty(defaultRedirectpath))
  94. {
  95. throw new ArgumentNullException("defaultRedirectpath");
  96. }
  97. ServerName = serverName;
  98. DefaultRedirectPath = defaultRedirectpath;
  99. _logger = logManager.GetLogger("HttpServer");
  100. ServiceStack.Logging.LogManager.LogFactory = new ServerLogFactory(logManager);
  101. EndpointHostConfig.Instance.ServiceStackHandlerFactoryPath = null;
  102. EndpointHostConfig.Instance.MetadataRedirectPath = "metadata";
  103. _containerAdapter = new ContainerAdapter(applicationHost);
  104. }
  105. /// <summary>
  106. /// The us culture
  107. /// </summary>
  108. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  109. /// <summary>
  110. /// Configures the specified container.
  111. /// </summary>
  112. /// <param name="container">The container.</param>
  113. public override void Configure(Container container)
  114. {
  115. JsConfig.DateHandler = JsonDateHandler.ISO8601;
  116. JsConfig.ExcludeTypeInfo = true;
  117. JsConfig.IncludeNullValues = false;
  118. SetConfig(new EndpointHostConfig
  119. {
  120. DefaultRedirectPath = DefaultRedirectPath,
  121. // Tell SS to bubble exceptions up to here
  122. WriteErrorsToResponse = false
  123. });
  124. container.Adapter = _containerAdapter;
  125. Plugins.Add(new SwaggerFeature());
  126. Plugins.Add(new CorsFeature());
  127. ResponseFilters.Add((req, res, dto) =>
  128. {
  129. var exception = dto as Exception;
  130. if (exception != null)
  131. {
  132. _logger.ErrorException("Error processing request for {0}", exception, req.RawUrl);
  133. if (!string.IsNullOrEmpty(exception.Message))
  134. {
  135. var error = exception.Message.Replace(Environment.NewLine, " ");
  136. error = RemoveControlCharacters(error);
  137. res.AddHeader("X-Application-Error-Code", error);
  138. }
  139. }
  140. if (dto is CompressedResult)
  141. {
  142. // Per Google PageSpeed
  143. // This instructs the proxies to cache two versions of the resource: one compressed, and one uncompressed.
  144. // The correct version of the resource is delivered based on the client request header.
  145. // This is a good choice for applications that are singly homed and depend on public proxies for user locality.
  146. res.AddHeader("Vary", "Accept-Encoding");
  147. }
  148. var hasOptions = dto as IHasOptions;
  149. if (hasOptions != null)
  150. {
  151. // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy
  152. string contentLength;
  153. if (hasOptions.Options.TryGetValue("Content-Length", out contentLength) && !string.IsNullOrEmpty(contentLength))
  154. {
  155. var length = long.Parse(contentLength, UsCulture);
  156. if (length > 0)
  157. {
  158. var response = (HttpListenerResponse)res.OriginalResponse;
  159. response.ContentLength64 = length;
  160. // Disable chunked encoding. Technically this is only needed when using Content-Range, but
  161. // anytime we know the content length there's no need for it
  162. response.SendChunked = false;
  163. }
  164. }
  165. }
  166. });
  167. }
  168. /// <summary>
  169. /// Removes the control characters.
  170. /// </summary>
  171. /// <param name="inString">The in string.</param>
  172. /// <returns>System.String.</returns>
  173. private static string RemoveControlCharacters(string inString)
  174. {
  175. if (inString == null) return null;
  176. var newString = new StringBuilder();
  177. foreach (var ch in inString)
  178. {
  179. if (!char.IsControl(ch))
  180. {
  181. newString.Append(ch);
  182. }
  183. }
  184. return newString.ToString();
  185. }
  186. /// <summary>
  187. /// Starts the Web Service
  188. /// </summary>
  189. /// <param name="urlBase">A Uri that acts as the base that the server is listening on.
  190. /// Format should be: http://127.0.0.1:8080/ or http://127.0.0.1:8080/somevirtual/
  191. /// Note: the trailing slash is required! For more info see the
  192. /// HttpListener.Prefixes property on MSDN.</param>
  193. /// <exception cref="System.ArgumentNullException">urlBase</exception>
  194. public override void Start(string urlBase)
  195. {
  196. if (string.IsNullOrEmpty(urlBase))
  197. {
  198. throw new ArgumentNullException("urlBase");
  199. }
  200. // *** Already running - just leave it in place
  201. if (IsStarted)
  202. {
  203. return;
  204. }
  205. if (Listener == null)
  206. {
  207. _logger.Info("Creating HttpListner");
  208. Listener = new HttpListener();
  209. }
  210. EndpointHost.Config.ServiceStackHandlerFactoryPath = HttpListenerRequestWrapper.GetHandlerPathIfAny(urlBase);
  211. UrlPrefix = urlBase;
  212. _logger.Info("Adding HttpListener Prefixes");
  213. Listener.Prefixes.Add(urlBase);
  214. IsStarted = true;
  215. _logger.Info("Starting HttpListner");
  216. Listener.Start();
  217. _logger.Info("Creating HttpListner observable stream");
  218. HttpListener = CreateObservableStream().Subscribe(ProcessHttpRequestAsync);
  219. }
  220. /// <summary>
  221. /// Creates the observable stream.
  222. /// </summary>
  223. /// <returns>IObservable{HttpListenerContext}.</returns>
  224. private IObservable<HttpListenerContext> CreateObservableStream()
  225. {
  226. return Observable.Create<HttpListenerContext>(obs =>
  227. Observable.FromAsync(() => Listener.GetContextAsync())
  228. .Subscribe(obs))
  229. .Repeat()
  230. .Retry()
  231. .Publish()
  232. .RefCount();
  233. }
  234. /// <summary>
  235. /// Processes incoming http requests by routing them to the appropiate handler
  236. /// </summary>
  237. /// <param name="context">The CTX.</param>
  238. private async void ProcessHttpRequestAsync(HttpListenerContext context)
  239. {
  240. LogHttpRequest(context);
  241. if (context.Request.IsWebSocketRequest)
  242. {
  243. await ProcessWebSocketRequest(context).ConfigureAwait(false);
  244. return;
  245. }
  246. RaiseReceiveWebRequest(context);
  247. await Task.Run(() =>
  248. {
  249. try
  250. {
  251. ProcessRequest(context);
  252. }
  253. catch (InvalidOperationException ex)
  254. {
  255. HandleException(context.Response, ex, 422);
  256. }
  257. catch (ResourceNotFoundException ex)
  258. {
  259. HandleException(context.Response, ex, 404);
  260. }
  261. catch (FileNotFoundException ex)
  262. {
  263. HandleException(context.Response, ex, 404);
  264. }
  265. catch (DirectoryNotFoundException ex)
  266. {
  267. HandleException(context.Response, ex, 404);
  268. }
  269. catch (UnauthorizedAccessException ex)
  270. {
  271. HandleException(context.Response, ex, 401);
  272. }
  273. catch (ArgumentException ex)
  274. {
  275. HandleException(context.Response, ex, 400);
  276. }
  277. catch (Exception ex)
  278. {
  279. HandleException(context.Response, ex, 500);
  280. }
  281. finally
  282. {
  283. context.Response.Close();
  284. }
  285. }).ConfigureAwait(false);
  286. }
  287. /// <summary>
  288. /// Processes the web socket request.
  289. /// </summary>
  290. /// <param name="ctx">The CTX.</param>
  291. /// <returns>Task.</returns>
  292. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  293. {
  294. try
  295. {
  296. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  297. if (WebSocketConnected != null)
  298. {
  299. WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger), Endpoint = ctx.Request.RemoteEndPoint.ToString() });
  300. }
  301. }
  302. catch (Exception ex)
  303. {
  304. _logger.ErrorException("AcceptWebSocketAsync error", ex);
  305. ctx.Response.StatusCode = 500;
  306. ctx.Response.Close();
  307. }
  308. }
  309. /// <summary>
  310. /// Logs the HTTP request.
  311. /// </summary>
  312. /// <param name="ctx">The CTX.</param>
  313. private void LogHttpRequest(HttpListenerContext ctx)
  314. {
  315. var log = new StringBuilder();
  316. log.AppendLine("Url: " + ctx.Request.Url);
  317. log.AppendLine("Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  318. var type = ctx.Request.IsWebSocketRequest ? "Web Socket" : "HTTP " + ctx.Request.HttpMethod;
  319. if (EnableHttpRequestLogging)
  320. {
  321. _logger.LogMultiline(type + " request received from " + ctx.Request.RemoteEndPoint, LogSeverity.Debug, log);
  322. }
  323. }
  324. /// <summary>
  325. /// Appends the error message.
  326. /// </summary>
  327. /// <param name="response">The response.</param>
  328. /// <param name="ex">The ex.</param>
  329. /// <param name="statusCode">The status code.</param>
  330. private void HandleException(HttpListenerResponse response, Exception ex, int statusCode)
  331. {
  332. _logger.ErrorException("Error processing request", ex);
  333. // This could fail, but try to add the stack trace as the body content
  334. try
  335. {
  336. //response.StatusCode = statusCode;
  337. response.Headers.Add("Status", statusCode.ToString(new CultureInfo("en-US")));
  338. response.Headers.Remove("Age");
  339. response.Headers.Remove("Expires");
  340. response.Headers.Remove("Cache-Control");
  341. response.Headers.Remove("Etag");
  342. response.Headers.Remove("Last-Modified");
  343. if (!string.IsNullOrEmpty(ex.Message))
  344. {
  345. response.AddHeader("X-Application-Error-Code", ex.Message);
  346. }
  347. var sb = new StringBuilder();
  348. sb.AppendLine("{");
  349. sb.AppendLine("\"ResponseStatus\":{");
  350. sb.AppendFormat(" \"ErrorCode\":{0},\n", ex.GetType().Name.EncodeJson());
  351. sb.AppendFormat(" \"Message\":{0},\n", ex.Message.EncodeJson());
  352. sb.AppendFormat(" \"StackTrace\":{0}\n", ex.StackTrace.EncodeJson());
  353. sb.AppendLine("}");
  354. sb.AppendLine("}");
  355. var sbBytes = sb.ToString().ToUtf8Bytes();
  356. response.OutputStream.Write(sbBytes, 0, sbBytes.Length);
  357. }
  358. catch (Exception errorEx)
  359. {
  360. _logger.ErrorException("Error processing failed request", errorEx);
  361. }
  362. }
  363. /// <summary>
  364. /// Overridable method that can be used to implement a custom hnandler
  365. /// </summary>
  366. /// <param name="context">The context.</param>
  367. /// <exception cref="System.NotImplementedException">Cannot execute handler: + handler + at PathInfo: + httpReq.PathInfo</exception>
  368. protected override void ProcessRequest(HttpListenerContext context)
  369. {
  370. if (string.IsNullOrEmpty(context.Request.RawUrl)) return;
  371. var operationName = context.Request.GetOperationName();
  372. var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
  373. var httpRes = new HttpListenerResponseWrapper(context.Response);
  374. var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);
  375. var url = context.Request.Url.ToString();
  376. var endPoint = context.Request.RemoteEndPoint;
  377. var serviceStackHandler = handler as IServiceStackHttpHandler;
  378. if (serviceStackHandler != null)
  379. {
  380. var restHandler = serviceStackHandler as RestHandler;
  381. if (restHandler != null)
  382. {
  383. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
  384. }
  385. serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
  386. LogResponse(context, url, endPoint);
  387. return;
  388. }
  389. throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
  390. }
  391. /// <summary>
  392. /// Logs the response.
  393. /// </summary>
  394. /// <param name="ctx">The CTX.</param>
  395. /// <param name="url">The URL.</param>
  396. /// <param name="endPoint">The end point.</param>
  397. private void LogResponse(HttpListenerContext ctx, string url, IPEndPoint endPoint)
  398. {
  399. if (!EnableHttpRequestLogging)
  400. {
  401. return;
  402. }
  403. var statusode = ctx.Response.StatusCode;
  404. var log = new StringBuilder();
  405. log.AppendLine(string.Format("Url: {0}", url));
  406. log.AppendLine("Headers: " + string.Join(",", ctx.Response.Headers.AllKeys.Select(k => k + "=" + ctx.Response.Headers[k])));
  407. var msg = "Http Response Sent (" + statusode + ") to " + endPoint;
  408. _logger.LogMultiline(msg, LogSeverity.Debug, log);
  409. }
  410. /// <summary>
  411. /// Creates the service manager.
  412. /// </summary>
  413. /// <param name="assembliesWithServices">The assemblies with services.</param>
  414. /// <returns>ServiceManager.</returns>
  415. protected override ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
  416. {
  417. var types = _restServices.Select(r => r.GetType()).ToArray();
  418. return new ServiceManager(new Container(), new ServiceController(() => types));
  419. }
  420. /// <summary>
  421. /// Shut down the Web Service
  422. /// </summary>
  423. public override void Stop()
  424. {
  425. if (HttpListener != null)
  426. {
  427. HttpListener.Dispose();
  428. HttpListener = null;
  429. }
  430. if (Listener != null)
  431. {
  432. Listener.Prefixes.Remove(UrlPrefix);
  433. }
  434. base.Stop();
  435. }
  436. /// <summary>
  437. /// The _supports native web socket
  438. /// </summary>
  439. private bool? _supportsNativeWebSocket;
  440. /// <summary>
  441. /// Gets a value indicating whether [supports web sockets].
  442. /// </summary>
  443. /// <value><c>true</c> if [supports web sockets]; otherwise, <c>false</c>.</value>
  444. public bool SupportsWebSockets
  445. {
  446. get
  447. {
  448. if (!_supportsNativeWebSocket.HasValue)
  449. {
  450. try
  451. {
  452. new ClientWebSocket();
  453. _supportsNativeWebSocket = true;
  454. }
  455. catch (PlatformNotSupportedException)
  456. {
  457. _supportsNativeWebSocket = false;
  458. }
  459. }
  460. return _supportsNativeWebSocket.Value;
  461. }
  462. }
  463. /// <summary>
  464. /// Gets or sets a value indicating whether [enable HTTP request logging].
  465. /// </summary>
  466. /// <value><c>true</c> if [enable HTTP request logging]; otherwise, <c>false</c>.</value>
  467. public bool EnableHttpRequestLogging { get; set; }
  468. /// <summary>
  469. /// Adds the rest handlers.
  470. /// </summary>
  471. /// <param name="services">The services.</param>
  472. public void Init(IEnumerable<IRestfulService> services)
  473. {
  474. _restServices.AddRange(services);
  475. _logger.Info("Calling EndpointHost.ConfigureHost");
  476. EndpointHost.ConfigureHost(this, ServerName, CreateServiceManager());
  477. _logger.Info("Calling ServiceStack AppHost.Init");
  478. Init();
  479. }
  480. }
  481. /// <summary>
  482. /// Class ContainerAdapter
  483. /// </summary>
  484. class ContainerAdapter : IContainerAdapter, IRelease
  485. {
  486. /// <summary>
  487. /// The _app host
  488. /// </summary>
  489. private readonly IApplicationHost _appHost;
  490. /// <summary>
  491. /// Initializes a new instance of the <see cref="ContainerAdapter" /> class.
  492. /// </summary>
  493. /// <param name="appHost">The app host.</param>
  494. public ContainerAdapter(IApplicationHost appHost)
  495. {
  496. _appHost = appHost;
  497. }
  498. /// <summary>
  499. /// Resolves this instance.
  500. /// </summary>
  501. /// <typeparam name="T"></typeparam>
  502. /// <returns>``0.</returns>
  503. public T Resolve<T>()
  504. {
  505. return _appHost.Resolve<T>();
  506. }
  507. /// <summary>
  508. /// Tries the resolve.
  509. /// </summary>
  510. /// <typeparam name="T"></typeparam>
  511. /// <returns>``0.</returns>
  512. public T TryResolve<T>()
  513. {
  514. return _appHost.TryResolve<T>();
  515. }
  516. /// <summary>
  517. /// Releases the specified instance.
  518. /// </summary>
  519. /// <param name="instance">The instance.</param>
  520. public void Release(object instance)
  521. {
  522. // Leave this empty so SS doesn't try to dispose our objects
  523. }
  524. }
  525. /// <summary>
  526. /// Class ServerLogFactory
  527. /// </summary>
  528. public class ServerLogFactory : ILogFactory
  529. {
  530. /// <summary>
  531. /// The _log manager
  532. /// </summary>
  533. private readonly ILogManager _logManager;
  534. /// <summary>
  535. /// Initializes a new instance of the <see cref="ServerLogFactory"/> class.
  536. /// </summary>
  537. /// <param name="logManager">The log manager.</param>
  538. public ServerLogFactory(ILogManager logManager)
  539. {
  540. _logManager = logManager;
  541. }
  542. /// <summary>
  543. /// Gets the logger.
  544. /// </summary>
  545. /// <param name="typeName">Name of the type.</param>
  546. /// <returns>ILog.</returns>
  547. public ILog GetLogger(string typeName)
  548. {
  549. return new ServerLogger(_logManager.GetLogger(typeName));
  550. }
  551. /// <summary>
  552. /// Gets the logger.
  553. /// </summary>
  554. /// <param name="type">The type.</param>
  555. /// <returns>ILog.</returns>
  556. public ILog GetLogger(Type type)
  557. {
  558. return GetLogger(type.Name);
  559. }
  560. }
  561. /// <summary>
  562. /// Class ServerLogger
  563. /// </summary>
  564. public class ServerLogger : ILog
  565. {
  566. /// <summary>
  567. /// The _logger
  568. /// </summary>
  569. private readonly ILogger _logger;
  570. /// <summary>
  571. /// Initializes a new instance of the <see cref="ServerLogger"/> class.
  572. /// </summary>
  573. /// <param name="logger">The logger.</param>
  574. public ServerLogger(ILogger logger)
  575. {
  576. _logger = logger;
  577. }
  578. /// <summary>
  579. /// Logs a Debug message and exception.
  580. /// </summary>
  581. /// <param name="message">The message.</param>
  582. /// <param name="exception">The exception.</param>
  583. public void Debug(object message, Exception exception)
  584. {
  585. _logger.ErrorException(GetMesssage(message), exception);
  586. }
  587. /// <summary>
  588. /// Logs a Debug message.
  589. /// </summary>
  590. /// <param name="message">The message.</param>
  591. public void Debug(object message)
  592. {
  593. _logger.Debug(GetMesssage(message));
  594. }
  595. /// <summary>
  596. /// Logs a Debug format message.
  597. /// </summary>
  598. /// <param name="format">The format.</param>
  599. /// <param name="args">The args.</param>
  600. public void DebugFormat(string format, params object[] args)
  601. {
  602. _logger.Debug(format, args);
  603. }
  604. /// <summary>
  605. /// Logs a Error message and exception.
  606. /// </summary>
  607. /// <param name="message">The message.</param>
  608. /// <param name="exception">The exception.</param>
  609. public void Error(object message, Exception exception)
  610. {
  611. _logger.ErrorException(GetMesssage(message), exception);
  612. }
  613. /// <summary>
  614. /// Logs a Error message.
  615. /// </summary>
  616. /// <param name="message">The message.</param>
  617. public void Error(object message)
  618. {
  619. _logger.Error(GetMesssage(message));
  620. }
  621. /// <summary>
  622. /// Logs a Error format message.
  623. /// </summary>
  624. /// <param name="format">The format.</param>
  625. /// <param name="args">The args.</param>
  626. public void ErrorFormat(string format, params object[] args)
  627. {
  628. _logger.Error(format, args);
  629. }
  630. /// <summary>
  631. /// Logs a Fatal message and exception.
  632. /// </summary>
  633. /// <param name="message">The message.</param>
  634. /// <param name="exception">The exception.</param>
  635. public void Fatal(object message, Exception exception)
  636. {
  637. _logger.FatalException(GetMesssage(message), exception);
  638. }
  639. /// <summary>
  640. /// Logs a Fatal message.
  641. /// </summary>
  642. /// <param name="message">The message.</param>
  643. public void Fatal(object message)
  644. {
  645. _logger.Fatal(GetMesssage(message));
  646. }
  647. /// <summary>
  648. /// Logs a Error format message.
  649. /// </summary>
  650. /// <param name="format">The format.</param>
  651. /// <param name="args">The args.</param>
  652. public void FatalFormat(string format, params object[] args)
  653. {
  654. _logger.Fatal(format, args);
  655. }
  656. /// <summary>
  657. /// Logs an Info message and exception.
  658. /// </summary>
  659. /// <param name="message">The message.</param>
  660. /// <param name="exception">The exception.</param>
  661. public void Info(object message, Exception exception)
  662. {
  663. _logger.ErrorException(GetMesssage(message), exception);
  664. }
  665. /// <summary>
  666. /// Logs an Info message and exception.
  667. /// </summary>
  668. /// <param name="message">The message.</param>
  669. public void Info(object message)
  670. {
  671. _logger.Info(GetMesssage(message));
  672. }
  673. /// <summary>
  674. /// Logs an Info format message.
  675. /// </summary>
  676. /// <param name="format">The format.</param>
  677. /// <param name="args">The args.</param>
  678. public void InfoFormat(string format, params object[] args)
  679. {
  680. _logger.Info(format, args);
  681. }
  682. /// <summary>
  683. /// Gets or sets a value indicating whether this instance is debug enabled.
  684. /// </summary>
  685. /// <value><c>true</c> if this instance is debug enabled; otherwise, <c>false</c>.</value>
  686. public bool IsDebugEnabled
  687. {
  688. get { return true; }
  689. }
  690. /// <summary>
  691. /// Logs a Warning message and exception.
  692. /// </summary>
  693. /// <param name="message">The message.</param>
  694. /// <param name="exception">The exception.</param>
  695. public void Warn(object message, Exception exception)
  696. {
  697. _logger.ErrorException(GetMesssage(message), exception);
  698. }
  699. /// <summary>
  700. /// Logs a Warning message.
  701. /// </summary>
  702. /// <param name="message">The message.</param>
  703. public void Warn(object message)
  704. {
  705. _logger.Warn(GetMesssage(message));
  706. }
  707. /// <summary>
  708. /// Logs a Warning format message.
  709. /// </summary>
  710. /// <param name="format">The format.</param>
  711. /// <param name="args">The args.</param>
  712. public void WarnFormat(string format, params object[] args)
  713. {
  714. _logger.Warn(format, args);
  715. }
  716. /// <summary>
  717. /// Gets the messsage.
  718. /// </summary>
  719. /// <param name="o">The o.</param>
  720. /// <returns>System.String.</returns>
  721. private string GetMesssage(object o)
  722. {
  723. return o == null ? string.Empty : o.ToString();
  724. }
  725. }
  726. }