jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more 
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. 
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with 
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
 
// .NET Compact Framework 1.0 has no support for reading assembly attributes
#if !NETCF
 
using System;
using System.Collections;
using System.Reflection;
using System.IO;
 
using log4net.Util;
using log4net.Repository;
using log4net.Repository.Hierarchy;
 
namespace log4net.Config
{
    /// <summary>
    /// Assembly level attribute to configure the <see cref="XmlConfigurator"/>.
    /// </summary>
    /// <remarks>
    /// <para>
    /// This attribute may only be used at the assembly scope and can only
    /// be used once per assembly.
    /// </para>
    /// <para>
    /// Use this attribute to configure the <see cref="XmlConfigurator"/>
    /// without calling one of the <see cref="XmlConfigurator.Configure()"/>
    /// methods.
    /// </para>
    /// <para>
    /// If neither of the <see cref="ConfigFile"/> or <see cref="ConfigFileExtension"/>
    /// properties are set the configuration is loaded from the application's .config file.
    /// If set the <see cref="ConfigFile"/> property takes priority over the
    /// <see cref="ConfigFileExtension"/> property. The <see cref="ConfigFile"/> property
    /// specifies a path to a file to load the config from. The path is relative to the
    /// application's base directory; <see cref="AppDomain.BaseDirectory"/>.
    /// The <see cref="ConfigFileExtension"/> property is used as a postfix to the assembly file name.
    /// The config file must be located in the  application's base directory; <see cref="AppDomain.BaseDirectory"/>.
    /// For example in a console application setting the <see cref="ConfigFileExtension"/> to
    /// <c>config</c> has the same effect as not specifying the <see cref="ConfigFile"/> or 
    /// <see cref="ConfigFileExtension"/> properties.
    /// </para>
    /// <para>
    /// The <see cref="Watch"/> property can be set to cause the <see cref="XmlConfigurator"/>
    /// to watch the configuration file for changes.
    /// </para>
    /// <note>
    /// <para>
    /// Log4net will only look for assembly level configuration attributes once.
    /// When using the log4net assembly level attributes to control the configuration 
    /// of log4net you must ensure that the first call to any of the 
    /// <see cref="log4net.Core.LoggerManager"/> methods is made from the assembly with the configuration
    /// attributes. 
    /// </para>
    /// <para>
    /// If you cannot guarantee the order in which log4net calls will be made from 
    /// different assemblies you must use programmatic configuration instead, i.e.
    /// call the <see cref="XmlConfigurator.Configure()"/> method directly.
    /// </para>
    /// </note>
    /// </remarks>
    /// <author>Nicko Cadell</author>
    /// <author>Gert Driesen</author>
    [AttributeUsage(AttributeTargets.Assembly)]
    [Serializable]
    public /*sealed*/ class XmlConfiguratorAttribute : ConfiguratorAttribute
    {
        //
        // Class is not sealed because DOMConfiguratorAttribute extends it while it is obsoleted
        // 
 
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <remarks>
        /// <para>
        /// Default constructor
        /// </para>
        /// </remarks>
        public XmlConfiguratorAttribute() : base(0) /* configurator priority 0 */
        {
        }
 
        #region Public Instance Properties
 
        /// <summary>
        /// Gets or sets the filename of the configuration file.
        /// </summary>
        /// <value>
        /// The filename of the configuration file.
        /// </value>
        /// <remarks>
        /// <para>
        /// If specified, this is the name of the configuration file to use with
        /// the <see cref="XmlConfigurator"/>. This file path is relative to the
        /// <b>application base</b> directory (<see cref="AppDomain.BaseDirectory"/>).
        /// </para>
        /// <para>
        /// The <see cref="ConfigFile"/> takes priority over the <see cref="ConfigFileExtension"/>.
        /// </para>
        /// </remarks>
        public string ConfigFile
        {
            get { return m_configFile; }
            set { m_configFile = value; }
        }
 
        /// <summary>
        /// Gets or sets the extension of the configuration file.
        /// </summary>
        /// <value>
        /// The extension of the configuration file.
        /// </value>
        /// <remarks>
        /// <para>
        /// If specified this is the extension for the configuration file.
        /// The path to the config file is built by using the <b>application 
        /// base</b> directory (<see cref="AppDomain.BaseDirectory"/>),
        /// the <b>assembly file name</b> and the config file extension.
        /// </para>
        /// <para>
        /// If the <see cref="ConfigFileExtension"/> is set to <c>MyExt</c> then
        /// possible config file names would be: <c>MyConsoleApp.exe.MyExt</c> or
        /// <c>MyClassLibrary.dll.MyExt</c>.
        /// </para>
        /// <para>
        /// The <see cref="ConfigFile"/> takes priority over the <see cref="ConfigFileExtension"/>.
        /// </para>
        /// </remarks>
        public string ConfigFileExtension
        {
            get { return m_configFileExtension; }
            set { m_configFileExtension = value; }
        }
 
        /// <summary>
        /// Gets or sets a value indicating whether to watch the configuration file.
        /// </summary>
        /// <value>
        /// <c>true</c> if the configuration should be watched, <c>false</c> otherwise.
        /// </value>
        /// <remarks>
        /// <para>
        /// If this flag is specified and set to <c>true</c> then the framework
        /// will watch the configuration file and will reload the config each time 
        /// the file is modified.
        /// </para>
        /// <para>
        /// The config file can only be watched if it is loaded from local disk.
        /// In a No-Touch (Smart Client) deployment where the application is downloaded
        /// from a web server the config file may not reside on the local disk
        /// and therefore it may not be able to watch it.
        /// </para>
        /// <note>
        /// Watching configuration is not supported on the SSCLI.
        /// </note>
        /// </remarks>
        public bool Watch
        {
            get { return m_configureAndWatch; }
            set { m_configureAndWatch = value; }
        }
 
        #endregion Public Instance Properties
 
        #region Override ConfiguratorAttribute
 
        /// <summary>
        /// Configures the <see cref="ILoggerRepository"/> for the specified assembly.
        /// </summary>
        /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
        /// <param name="targetRepository">The repository to configure.</param>
        /// <remarks>
        /// <para>
        /// Configure the repository using the <see cref="XmlConfigurator"/>.
        /// The <paramref name="targetRepository"/> specified must extend the <see cref="Hierarchy"/>
        /// class otherwise the <see cref="XmlConfigurator"/> will not be able to
        /// configure it.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentOutOfRangeException">The <paramref name="targetRepository" /> does not extend <see cref="Hierarchy"/>.</exception>
        override public void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository)
        {
            IList configurationMessages = new ArrayList();
 
            using (new LogLog.LogReceivedAdapter(configurationMessages))
            {
                string applicationBaseDirectory = null;
                try
                {
                    applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
                }
                catch
                {
                    // Ignore this exception because it is only thrown when ApplicationBaseDirectory is a file
                    // and the application does not have PathDiscovery permission
                }
 
                if (applicationBaseDirectory == null || (new Uri(applicationBaseDirectory)).IsFile)
                {
                    ConfigureFromFile(sourceAssembly, targetRepository);
                }
                else
                {
                    ConfigureFromUri(sourceAssembly, targetRepository);
                }
            }
 
            targetRepository.ConfigurationMessages = configurationMessages;
        }
 
        #endregion
 
        /// <summary>
        /// Attempt to load configuration from the local file system
        /// </summary>
        /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
        /// <param name="targetRepository">The repository to configure.</param>
        private void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository)
        {
            // Work out the full path to the config file
            string fullPath2ConfigFile = null;
            
            // Select the config file
            if (m_configFile == null || m_configFile.Length == 0)
            {
                if (m_configFileExtension == null || m_configFileExtension.Length == 0)
                {
                    // Use the default .config file for the AppDomain
                    try
                    {
                        fullPath2ConfigFile = SystemInfo.ConfigurationFileLocation;
                    }
                    catch(Exception ex)
                    {
                        LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex);
                    }
                }
                else
                {
                    // Force the extension to start with a '.'
                    if (m_configFileExtension[0] != '.')
                    {
                        m_configFileExtension = "." + m_configFileExtension;
                    }
 
                    string applicationBaseDirectory = null;
                    try
                    {
                        applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
                    }
                    catch(Exception ex)
                    {
                        LogLog.Error(declaringType, "Exception getting ApplicationBaseDirectory. Must be able to resolve ApplicationBaseDirectory and AssemblyFileName when ConfigFileExtension property is set.", ex);
                    }
 
                    if (applicationBaseDirectory != null)
                    {
                        fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, SystemInfo.AssemblyFileName(sourceAssembly) + m_configFileExtension);
                    }
                }
            }
            else
            {
                string applicationBaseDirectory = null;
                try
                {
                    applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
                }
                catch(Exception ex)
                {
                    LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+m_configFile+"] will be treated as an absolute path.", ex);
                }
 
                if (applicationBaseDirectory != null)
                {
                    // Just the base dir + the config file
                    fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, m_configFile);
                }
                else
                {
                    fullPath2ConfigFile = m_configFile;
                }
            }
 
            if (fullPath2ConfigFile != null)
            {
                ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile));
            }
        }
 
        /// <summary>
        /// Configure the specified repository using a <see cref="FileInfo"/>
        /// </summary>
        /// <param name="targetRepository">The repository to configure.</param>
        /// <param name="configFile">the FileInfo pointing to the config file</param>
        private void ConfigureFromFile(ILoggerRepository targetRepository, FileInfo configFile)
        {
#if (SSCLI)
            if (m_configureAndWatch)
            {
                LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file not supported on SSCLI");
            }
            XmlConfigurator.Configure(targetRepository, configFile);
#else
            // Do we configure just once or do we configure and then watch?
            if (m_configureAndWatch)
            {
                XmlConfigurator.ConfigureAndWatch(targetRepository, configFile);
            }
            else
            {
                XmlConfigurator.Configure(targetRepository, configFile);
            }
#endif
        }
 
        /// <summary>
        /// Attempt to load configuration from a URI
        /// </summary>
        /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
        /// <param name="targetRepository">The repository to configure.</param>
        private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository)
        {
            // Work out the full path to the config file
            Uri fullPath2ConfigFile = null;
            
            // Select the config file
            if (m_configFile == null || m_configFile.Length == 0)
            {
                if (m_configFileExtension == null || m_configFileExtension.Length == 0)
                {
                    string systemConfigFilePath = null;
                    try
                    {
                        systemConfigFilePath = SystemInfo.ConfigurationFileLocation;
                    }
                    catch(Exception ex)
                    {
                        LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex);
                    }
 
                    if (systemConfigFilePath != null)
                    {
                        Uri systemConfigFileUri = new Uri(systemConfigFilePath);
 
                        // Use the default .config file for the AppDomain
                        fullPath2ConfigFile = systemConfigFileUri;
                    }
                }
                else
                {
                    // Force the extension to start with a '.'
                    if (m_configFileExtension[0] != '.')
                    {
                        m_configFileExtension = "." + m_configFileExtension;
                    }
 
                    string systemConfigFilePath = null;
                    try
                    {
                        systemConfigFilePath = SystemInfo.ConfigurationFileLocation;
                    }
                    catch(Exception ex)
                    {
                        LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", ex);
                    }
 
                    if (systemConfigFilePath != null)
                    {
                        UriBuilder builder = new UriBuilder(new Uri(systemConfigFilePath));
 
                        // Remove the current extension from the systemConfigFileUri path
                        string path = builder.Path;
                        int startOfExtension = path.LastIndexOf(".");
                        if (startOfExtension >= 0)
                        {
                            path = path.Substring(0, startOfExtension);
                        }
                        path += m_configFileExtension;
 
                        builder.Path = path;
                        fullPath2ConfigFile = builder.Uri;
                    }
                }
            }
            else
            {
                string applicationBaseDirectory = null;
                try
                {
                    applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
                }
                catch(Exception ex)
                {
                    LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+m_configFile+"] will be treated as an absolute URI.", ex);
                }
 
                if (applicationBaseDirectory != null)
                {
                    // Just the base dir + the config file
                    fullPath2ConfigFile = new Uri(new Uri(applicationBaseDirectory), m_configFile);
                }
                else
                {
                    fullPath2ConfigFile = new Uri(m_configFile);
                }
            }
 
            if (fullPath2ConfigFile != null)
            {
                if (fullPath2ConfigFile.IsFile)
                {
                    // The m_configFile could be an absolute local path, therefore we have to be
                    // prepared to switch back to using FileInfos here
                    ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath));
                }
                else
                {
                    if (m_configureAndWatch)
                    {
                        LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI");
                    }
                    XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile);
                }
            }
        }
 
        #region Private Instance Fields
 
        private string m_configFile = null;
        private string m_configFileExtension = null;
        private bool m_configureAndWatch = false;
 
        #endregion Private Instance Fields
 
        #region Private Static Fields
 
        /// <summary>
        /// The fully qualified type of the XmlConfiguratorAttribute class.
        /// </summary>
        /// <remarks>
        /// Used by the internal logger to record the Type of the
        /// log message.
        /// </remarks>
        private readonly static Type declaringType = typeof(XmlConfiguratorAttribute);
 
        #endregion Private Static Fields
    }
}
 
#endif // !NETCF