Source

flioops-net / FLiOOPS.Logging / PyLogging.cs

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
using ComLib.Configuration;
using ComLib.Logging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;

namespace FLiOOPS.Logging
{
    /// <summary>
    /// A logging setup implementation that mimics the rules 
    /// considered by Python standard <code>logging</code> module. 
    /// However, under some circumstances it can go beyond 
    /// this specification and sometimes it may adopt .NET-specific 
    /// rules and notations. This means that even if it will always 
    /// be inspired in Python implementation, it is not designed 
    /// to be interoperable with Python logging configuration files
    /// (e.g. because of different object loading mechanisms, 
    /// syntax and semantics).
    /// </summary>
    /// <remarks>
    /// Python logging API is documented and available at this address
    /// http://www.python.org/dev/peps/pep-0282 .
    /// </remarks>
    class PythonLoggingSetup : ILogSetup
    {
        protected IConfigSection section = null;
        protected static Dictionary<object, object> default_opts {
            get
            {
                return new Dictionary<object,object>()
                    {
                        {"overwrite", OverwriteMode.CLEAR}
                    };
            }
        }

        #region ILogSetup Members

        /// <summary>
        /// Install the equivalent of Python logging setup
        /// globally.
        /// </summary>
        /// <remarks>
        /// If no configuration source has been bound to this 
        /// instance (<see cref="PythonLoggingSetup.Load(ComLib.Configuration.IConfigSection)"/>) 
        /// then install the equivalent of Python default logging 
        /// setup globally. Otherwise, it considers sections 
        /// rules to recreate a custom logging environment.
        /// </remarks>
        /// <exception cref="System.Configuration.ConfigurationException">
        /// A configuration error is raised is a name used for 
        /// cross-reference purposes cannot be resolved.
        /// </exception>
        void ILogSetup.DefaultSetup()
        {
            (this as ILogSetup).CustomSetup(
                new Dictionary<object, object>() {
                    {"overwrite" , OverwriteMode.CLEAR}
                });
        }

        /// <summary>
        /// Install the equivalent of Python logging setup
        /// globally.
        /// </summary>
        /// <param name="options">
        /// This class does not define specific options.
        /// See <seealso cref="ILogSetup.CustomSetup(IDictionary{object, object})"/>
        /// for standard options.
        /// </param>
        /// <remarks>
        /// The process may leave the loggers hierarchy in an 
        /// partial intermediate state if e.g. an exception is 
        /// raised during the configuration process.
        /// <para>
        /// If <c>"overwrite"</c> entry in <paramref name="options"/> 
        /// is set to <see cref="OverwriteMode.CLEAR"/> then there 
        /// will be no side effects. This means that the whole 
        /// configuration will be applied if the method returns 
        /// successfully.
        /// </para>
        /// <para>
        /// If <c>"overwrite"</c> entry in <paramref name="options"/> 
        /// is set to <see cref="OverwriteMode.OVERWRITE"/> 
        /// or <see cref="OverwriteMode.IGNORE"/> this
        /// method will try to apply so many rules as possible. 
        /// This means that only part of the configuration 
        /// may be applied if the method raises an exception.
        /// </para>
        /// </remarks>
        void ILogSetup.CustomSetup(IDictionary<object, object> options)
        {
            object modename;
            OverwriteMode mode = OverwriteMode.CLEAR;
            if (options.TryGetValue("overwrite", out modename))
                mode = (OverwriteMode)Enum.Parse(typeof(OverwriteMode), (string)modename);
            options["overwrite"] = (int) mode;
            if (section == null)
                default_setup(options);
            else
                section_setup(options);
        }
        
        /// <summary>
        /// Load logging setup rules from configuration source.
        /// </summary>
        /// <param name="config">
        /// Its sections are used to build log sources and arrange 
        /// them in such a way that a consistent hierarchy of loggers 
        /// may be built using a single method call.
        /// </param>
        void ILogSetup.Load(IConfigSection config)
        {
            section = config;
        }

        #endregion

        #region Internal methods

        /// <summary>
        /// Setup logging in a way similar to Python root 
        /// logger default configuration. Basically this means 
        /// you'll end up with an empty <c>"root"</c> logger 
        /// installed.
        /// </summary>
        /// <param name="options">
        /// Supported options listed below (see 
        /// <seealso cref="ILogSetup.CustomSetup(IDictionary{object, object})"/>
        /// for further details).
        /// 
        /// <list type="table">
        /// <item>
        ///     <term>overwrite</term>
        ///     <description>
        ///     Flag to control whether to overwrite existing loggers.
        ///     <seealso cref="OverwriteMode"/>
        ///     </description>
        /// </item>
        /// </list>
        /// 
        /// </param>
        protected virtual void default_setup(IDictionary<object, object> options)
        {
            OverwriteMode mode = (OverwriteMode)options["overwrite"];
            bool overwrite = true;
            switch (mode)
            { 
                case OverwriteMode.CLEAR:
                    Logger.Clear();
                    break;
                case OverwriteMode.OVERWRITE:
                    break;
                case OverwriteMode.IGNORE:
                    overwrite = Logger.Get("root") == null;
                    break;
            }
            if (overwrite)
            {
                LogMulti root = new LogMulti("default", new List<ILog>());
                Logger.Add(root);
                root.Name = "root";
                Logger.Add(root);
            }
        }

        /// <summary>
        /// Setup logging using custom configuration data.
        /// </summary>
        protected virtual void section_setup(IDictionary<object, object> options)
        {
            IDictionary<string, ILogFormatter> flist = _create_formatters();
            IDictionary<string, ILog> hlist = _install_handlers(flist);
            _install_loggers(hlist, options);
        }

        /// <summary>
        /// Create and install loggers specified in configuration source.
        /// </summary>
        /// <param name="hlist">
        /// List of (previously loaded 
        /// <see cref="PythonLoggingSetup._install_handlers(IDictionary<string, LogFormatter>)"/>) 
        /// log sources.
        /// </param>
        /// <param name="options">
        /// Custom options <seealso cref="PythonLoggingSetup.CustomSetup()"/>.
        /// </param>
        /// <remarks>
        /// Partial configuration may happen if exception is raised.
        /// </remarks>
        protected virtual void _install_loggers(IDictionary<string, ILog> hlist, 
            IDictionary<object, object> options)
        {
            // Configure the root first
            string[] llist = section.GetDefault("loggers", "keys", "")
                .Trim().Split(new char[] {','})
                .Distinct()
                .Where(x => !x.Equals("root"))
                .Select(x => x.Trim()).ToArray();
            string sectname = "logger_root";
            OverwriteMode overwrite = (OverwriteMode)options["overwrite"];
            ILogMulti root = (overwrite == OverwriteMode.CLEAR)?
                new LogMulti("default", new List<ILog>(llist.Length)) :
                Logger.Default;
            ILog log = root;
            if (section.Contains(sectname, "level"))
            {
                try
                {
                    root.Level = LogHelper.GetLogLevel(section.Get<string>(sectname, "level"));
                }
                catch (Exception exc)
                { 
                    throw new ConfigurationException("Invalid logging level name", exc);
                }
            }
            
            string[] hids = section.GetDefault<string>(sectname, "handlers", "")
                .Split(new char[] {','}).Distinct().Select(x => x.Trim()).ToArray();
            switch (overwrite)
            {
                case OverwriteMode.CLEAR:
                case OverwriteMode.OVERWRITE:
                    foreach (ILog source in hids.Select(x => hlist[x]))
                        root.Append(source);
                    break;
                case OverwriteMode.IGNORE:
                    foreach (string hand in hids)
                        if (root[hand] == null)
                            root.Append(hlist[hand]);
                    break;
            }

            // and now the others...
            foreach (string lognm in llist)
            {
                sectname = "logger_" + lognm;
                try
                {
                    string qn = section.Get<string>(sectname, "qualname");
                }
                catch (KeyNotFoundException exc)
                { 
                    throw new ConfigurationException("Logger qualified name missing in " + lognm,
                        exc);
                }
                
                // TODO: Does ILog support propagation control
                //if "propagate" in opts:
                //    propagate = cp.getint(sectname, "propagate")
                //else:
                //    propagate = 1
            }

    // Former Python code borrowed from stdlib !!! 

    //for log in llist:
    //    logger = logging.getLogger(qn)
    //    if qn in existing:
    //        i = existing.index(qn)
    //        prefixed = qn + "."
    //        pflen = len(prefixed)
    //        num_existing = len(existing)
    //        i = i + 1 # look at the entry after qn
    //        while (i < num_existing) and (existing[i][:pflen] == prefixed):
    //            child_loggers.append(existing[i])
    //            i = i + 1
    //        existing.remove(qn)
    //    if "level" in opts:
    //        level = cp.get(sectname, "level")
    //        logger.setLevel(logging._levelNames[level])
    //    for h in logger.handlers[:]:
    //        logger.removeHandler(h)
    //    logger.propagate = propagate
    //    logger.disabled = 0
    //    hlist = cp.get(sectname, "handlers")
    //    if len(hlist):
    //        hlist = string.split(hlist, ",")
    //        hlist = _strip_spaces(hlist)
    //        for hand in hlist:
    //            logger.addHandler(handlers[hand])

    //#Disable any old loggers. There's no point deleting
    //#them as other threads may continue to hold references
    //#and by disabling them, you stop them doing any logging.
    //#However, don't disable children of named loggers, as that's
    //#probably not what was intended by the user.
    //for log in existing:
    //    logger = root.manager.loggerDict[log]
    //    if log in child_loggers:
    //        logger.level = logging.NOTSET
    //        logger.handlers = []
    //        logger.propagate = 1
    //    elif disable_existing_loggers:
    //        logger.disabled = 1
        }

        /// <summary>
        /// Install and return log sources
        /// </summary>
        /// <param name="flist">
        /// Formatters list (<seealso cref="PythonLoggingSetup._create_formatters()"/>)
        /// </param>
        /// <returns>
        /// A list of log sources setup according to rules read 
        /// from configuration source. May be null if no log 
        /// source is defined.
        /// </returns>
        protected virtual IDictionary<string, ILog> _install_handlers(
            IDictionary<string, ILogFormatter> flist)
        {
            string[] hlist = section.GetDefault<string>("handlers", "keys", "")
                .Trim().Split(new char[] { ',' }).Select(x => x.Trim()).ToArray();
            if (hlist.Length == 0)
                return null;
            IDictionary<string, ILog> handlers = new Dictionary<string, ILog>(hlist.Length);

            // TODO: ???
            // fixups = [] #for inter-handler references

            foreach (string hand in hlist)
            {
                string sectname = "handler_" + hand;
                string klass = section.GetDefault<string>(sectname, "class", "");
                string fmt = section.GetDefault<string>(sectname, "formatter", "");
                object[] args = section.GetDefault<string>(sectname, "args", "")
                    .Trim().Split(new char[] { ',' }).Select(x => _resolve(x.Trim(), null)).ToArray();

                ILog source = _resolve(klass, null, args) as ILog;
                // FIXME: Name readonly !!!
                //source.Name = hand;

                string levelname = section.GetDefault<string>(sectname, "level", "");
                LogLevel level = LogLevel.Info;
                try
                {
                    level = LogHelper.GetLogLevel(levelname);
                }
                catch (Exception)
                { }
                source.Level = level;
                if (!string.IsNullOrEmpty(fmt))
                    try
                    {
                        ILogFormatter f = flist[fmt];
                        // TODO: Bind the formatter to this log source.
                    }
                    catch (KeyNotFoundException exc)
                    {
                        throw new ConfigurationException("Unknown formatter name: " + fmt, exc);
                    }

                // TODO: What about this MemoryHandler stuff ?
                //if issubclass(klass, logging.handlers.MemoryHandler):
                //    if "target" in opts:
                //        target = cp.get(sectname,"target")
                //    else:
                //        target = ""
                //    if len(target): #the target handler may not be loaded yet, so keep for later...
                //        fixups.append((h, target))

                handlers[hand] = source;
            }

            // TODO: Follow-up to the previous handlers stuff
            //#now all handlers are loaded, fixup inter-handler references...
            //for h, t in fixups:
            //    h.setTarget(handlers[t])

            return handlers;
        }

        // TODO: Assign correct value
        const string DEFAULT_FMTSTR = "";
        const string DEFAULT_DATESTR = "";

        /// <summary>
        /// Create and return formatters
        /// </summary>
        /// <returns>Dictionary mapping formatters using identifiers</returns>
        protected virtual IDictionary<string, ILogFormatter> _create_formatters()
        { 
            string  flist = section.GetDefault<string>("formatters", "keys", "");
            flist = flist.Trim();
            if (string.IsNullOrEmpty(flist))
                return null;
            string[] fids = flist.Split(new char[] {','}).Select(x => x.Trim()).ToArray();
            IDictionary<string, ILogFormatter> formatters = 
                new Dictionary<string, ILogFormatter>(fids.Length);
            foreach (string form in fids)
            {
                string sectname = "formatter_" + form;
                string fs = section.GetDefault<string>(sectname, "format", 
                    DEFAULT_FMTSTR);
                string dfs = section.GetDefault<string>(sectname, "datefmt", 
                    DEFAULT_DATESTR);
                string fmtcls = section.GetDefault<string>(sectname, "class", "");
                
                // TODO: Finish
                //ILogFormatter logfmt = _resolve(fmtcls, typeof(), fs, dfs) as ILogFormatter;
                //formatters[form] = logfmt;
            }
            return formatters;
        }

        /// <summary>
        /// Instantiate an object specified in a configuration file.
        /// </summary>
        /// <param name="typename">
        /// Full name of the target type that should be instantiated.
        /// Used to lookup the type definition following .NET built-in 
        /// Fully Qualified Type Names syntax.
        /// </param>
        /// <param name="deftype">
        /// Default type used in case <paramref name="typename"/> is 
        /// <c>null</c> or <c>string.Empty</c> .
        /// </param>
        /// <param name="args">
        /// Objects array used to identify a constructor which will be
        /// invoked by supplying them in as positional arguments.
        /// </param>
        /// <returns>
        /// <c>Object</c> instance obtained after invoking the 
        /// corresponding constructor of the target <paramref name="typename"/>
        /// or default type (i.e. <paramref name="deftype"/>).
        /// </returns>
        protected virtual object _resolve(string typename, Type deftype, params object[] args)
        {
            Type target;
            
            if (string.IsNullOrEmpty(typename))
            {
                target = deftype;
            }
            // TODO: Load and instantiate object using `target` type
            return null;
        }

        #endregion
    }
}