summaryrefslogtreecommitdiff
path: root/src/main/cpp/hierarchy.cpp
blob: fc80d7725a510095648d233e3253d03331274de9 (plain)
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
/*
 * 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.
 */

#if defined(_MSC_VER)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif

#include <log4cxx/logstring.h>
#include <log4cxx/spi/loggerfactory.h>
#include <log4cxx/hierarchy.h>
#include <log4cxx/defaultloggerfactory.h>
#include <log4cxx/logger.h>
#include <log4cxx/spi/hierarchyeventlistener.h>
#include <log4cxx/level.h>
#include <algorithm>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/appender.h>
#include <log4cxx/helpers/synchronized.h>
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/stringhelper.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/helpers/aprinitializer.h>
#include <log4cxx/defaultconfigurator.h>
#include <log4cxx/spi/rootlogger.h>
#include <apr_atomic.h>
#include "assert.h"


using namespace log4cxx;
using namespace log4cxx::spi;
using namespace log4cxx::helpers;

IMPLEMENT_LOG4CXX_OBJECT(Hierarchy)

Hierarchy::Hierarchy() :
pool(),
mutex(pool),
loggers(new LoggerMap()),
provisionNodes(new ProvisionNodeMap())
{
        synchronized sync(mutex);
        root = new RootLogger(pool, Level::getDebug());
        root->setHierarchy(this);
        defaultFactory = new DefaultLoggerFactory();
        emittedNoAppenderWarning = false;
        configured = false;
        thresholdInt = Level::ALL_INT;
        threshold = Level::getAll();
        emittedNoResourceBundleWarning = false;
}

Hierarchy::~Hierarchy()
{
// TODO LOGCXX-430
// https://issues.apache.org/jira/browse/LOGCXX-430?focusedCommentId=15175254&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-15175254
#ifndef APR_HAS_THREADS
	delete loggers;
	delete provisionNodes;
#endif
}

void Hierarchy::addRef() const {
    ObjectImpl::addRef();
}

void Hierarchy::releaseRef() const {
    ObjectImpl::releaseRef();
}

void Hierarchy::addHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener)
{
        synchronized sync(mutex);
        if (std::find(listeners.begin(), listeners.end(), listener) != listeners.end())
        {
                LogLog::warn(LOG4CXX_STR("Ignoring attempt to add an existent listener."));
        }
        else
        {
                listeners.push_back(listener);
        }
}

void Hierarchy::clear()
{
        synchronized sync(mutex);
        loggers->clear();
}

void Hierarchy::emitNoAppenderWarning(const LoggerPtr& logger)
{
       bool emitWarning = false;
       {
           synchronized sync(mutex);
           emitWarning = !emittedNoAppenderWarning;
           emittedNoAppenderWarning = true;
       }

        // No appender in hierarchy, warn user only once.
        if(emitWarning)
        {
                LogLog::warn(((LogString) LOG4CXX_STR("No appender could be found for logger ("))
                   + logger->getName() + LOG4CXX_STR(")."));
                LogLog::warn(LOG4CXX_STR("Please initialize the log4cxx system properly."));
        }
}


LoggerPtr Hierarchy::exists(const LogString& name)
{
        synchronized sync(mutex);

        LoggerPtr logger;
        LoggerMap::iterator it = loggers->find(name);
        if (it != loggers->end())
        {
                logger = it->second;
        }


        return logger;
}

void Hierarchy::setThreshold(const LevelPtr& l)
{
        if (l != 0)
        {
            synchronized sync(mutex);
            thresholdInt = l->toInt();
            threshold = l;
            if (thresholdInt != Level::ALL_INT) {
               setConfigured(true);
            }
        }
}

void Hierarchy::setThreshold(const LogString& levelStr) {
        LevelPtr l(Level::toLevelLS(levelStr, 0));

        if(l != 0)
        {
                setThreshold(l);
        }
        else
        {
                LogLog::warn(((LogString) LOG4CXX_STR("No level could be found named \""))
                    + levelStr + LOG4CXX_STR("\"."));
        }
}

void Hierarchy::fireAddAppenderEvent(const LoggerPtr& logger, const AppenderPtr& appender)
{
    setConfigured(true);
    HierarchyEventListenerList clonedList;
    {
       synchronized sync(mutex);
       clonedList = listeners;
    }

    HierarchyEventListenerList::iterator it, itEnd = clonedList.end();
    HierarchyEventListenerPtr listener;

    for(it = clonedList.begin(); it != itEnd; it++)
        {
                listener = *it;
                listener->addAppenderEvent(logger, appender);
        }
}

void Hierarchy::fireRemoveAppenderEvent(const LoggerPtr& logger, const AppenderPtr& appender)

{
    HierarchyEventListenerList clonedList;
    {
       synchronized sync(mutex);
       clonedList = listeners;
    }
    HierarchyEventListenerList::iterator it, itEnd = clonedList.end();
    HierarchyEventListenerPtr listener;

    for(it = clonedList.begin(); it != itEnd; it++)
        {
                listener = *it;
                listener->removeAppenderEvent(logger, appender);
        }
}

const LevelPtr& Hierarchy::getThreshold() const
{
        return threshold;
}

LoggerPtr Hierarchy::getLogger(const LogString& name)
{
        return getLogger(name, defaultFactory);
}

LoggerPtr Hierarchy::getLogger(const LogString& name,
     const spi::LoggerFactoryPtr& factory)
{
        synchronized sync(mutex);

        LoggerMap::iterator it = loggers->find(name);

        if (it != loggers->end())
        {
                return it->second;
        }
        else
        {
                LoggerPtr logger(factory->makeNewLoggerInstance(pool, name));
                logger->setHierarchy(this);
                loggers->insert(LoggerMap::value_type(name, logger));

                ProvisionNodeMap::iterator it2 = provisionNodes->find(name);
                if (it2 != provisionNodes->end())
                {
                        updateChildren(it2->second, logger);
                        provisionNodes->erase(it2);
                }

                updateParents(logger);
                return logger;
        }

}

LoggerList Hierarchy::getCurrentLoggers() const
{
        synchronized sync(mutex);

        LoggerList v;
        LoggerMap::const_iterator it, itEnd = loggers->end();

        for (it = loggers->begin(); it != itEnd; it++)
        {
                v.push_back(it->second);
        }


        return v;
}

LoggerPtr Hierarchy::getRootLogger() const
{
        return root;
}

bool Hierarchy::isDisabled(int level) const
{
   if(!configured) {
      synchronized sync(mutex);
      if (!configured) {
        DefaultConfigurator::configure(
            const_cast<Hierarchy*>(this));
      }
   }

   return thresholdInt > level;
}


void Hierarchy::resetConfiguration()
{
        synchronized sync(mutex);

        getRootLogger()->setLevel(Level::getDebug());
        root->setResourceBundle(0);
        setThreshold(Level::getAll());

        shutdown(); // nested locks are OK

        LoggerList loggers1 = getCurrentLoggers();
        LoggerList::iterator it, itEnd = loggers1.end();

        for (it = loggers1.begin(); it != itEnd; it++)
        {
                LoggerPtr& logger = *it;
                logger->setLevel(0);
                logger->setAdditivity(true);
                logger->setResourceBundle(0);
        }

        //rendererMap.clear();
}

void Hierarchy::shutdown()
{
      synchronized sync(mutex);

      setConfigured(false);

        LoggerPtr root1 = getRootLogger();

        // begin by closing nested appenders
        root1->closeNestedAppenders();

        LoggerList loggers1 = getCurrentLoggers();
        LoggerList::iterator it, itEnd = loggers1.end();

        for (it = loggers1.begin(); it != itEnd; it++)
        {
                LoggerPtr& logger = *it;
                logger->closeNestedAppenders();
        }

        // then, remove all appenders
        root1->removeAllAppenders();
        for (it = loggers1.begin(); it != itEnd; it++)
        {
                LoggerPtr& logger = *it;
                logger->removeAllAppenders();
        }
}


void Hierarchy::updateParents(LoggerPtr logger)
{
        synchronized sync(mutex);
        const LogString name(logger->getName());
        int length = name.size();
        bool parentFound = false;


        // if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z"
        for(size_t i = name.find_last_of(0x2E /* '.' */, length-1);
            (i != LogString::npos) && (i != 0);
            i = name.find_last_of(0x2E /* '.' */, i-1))
        {
                LogString substr = name.substr(0, i);

                LoggerMap::iterator it = loggers->find(substr);
                if(it != loggers->end())
                {
                        parentFound = true;
                        logger->parent = it->second;
                        break; // no need to update the ancestors of the closest ancestor
                }
                else
                {
                        ProvisionNodeMap::iterator it2 = provisionNodes->find(substr);
                        if (it2 != provisionNodes->end())
                        {
                                it2->second.push_back(logger);
                        }
                        else
                        {
                                ProvisionNode node(1, logger);
                                provisionNodes->insert(
                                        ProvisionNodeMap::value_type(substr, node));
                        }
                }
        }

        // If we could not find any existing parents, then link with root.
        if(!parentFound)
        {
                logger->parent = root;
        }
}

void Hierarchy::updateChildren(ProvisionNode& pn, LoggerPtr logger)
{

        ProvisionNode::iterator it, itEnd = pn.end();

        for(it = pn.begin(); it != itEnd; it++)
        {
                LoggerPtr& l = *it;

                // Unless this child already points to a correct (lower) parent,
                // make cat.parent point to l.parent and l.parent to cat.
                if(!StringHelper::startsWith(l->parent->name, logger->name))
                {
                        logger->parent = l->parent;
                        l->parent = logger;
                }
        }
}

void Hierarchy::setConfigured(bool newValue) {
    synchronized sync(mutex);
    configured = newValue;
}

bool Hierarchy::isConfigured() {
    return configured;
}