Add ability to save logs in a file

Change-Id: I9b557f193281461357ab4176103dc3c985cf5197
This commit is contained in:
Alexander Gorodnev 2014-01-21 17:02:41 +04:00
parent 1b3877c971
commit f2d7ecd46d
3 changed files with 57 additions and 4 deletions

View File

@ -54,6 +54,7 @@ Formatter = logging.Formatter
# Handlers
StreamHandler = logging.StreamHandler
FileHandler = logging.FileHandler
class TermFormatter(logging.Formatter):
@ -100,12 +101,24 @@ class TermAdapter(logging.LoggerAdapter):
logging.LoggerAdapter.__init__(self, logger, dict())
def setupLogging(log_level, format='%(levelname)s: @%(name)s : %(message)s'):
def setupLogging(log_level,
format='%(levelname)s: @%(name)s : %(message)s',
log_name='/var/log/anvil.log'):
root_logger = getLogger().logger
console_formatter = TermFormatter(format)
console_logger = StreamHandler(sys.stdout)
console_logger.setFormatter(TermFormatter(format))
console_logger.setLevel(log_level)
console_logger.setFormatter(console_formatter)
root_logger.addHandler(console_logger)
root_logger.setLevel(log_level)
file_formatter = logging.Formatter('%(asctime)s : ' + format)
file_logger = FileHandler(log_name)
file_logger.setFormatter(file_formatter)
file_logger.setLevel(DEBUG)
root_logger.addHandler(file_logger)
root_logger.setLevel(DEBUG)
def getLogger(name='anvil'):

38
anvil/tests/test_log.py Normal file
View File

@ -0,0 +1,38 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# Licensed 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.
import os
import tempfile
import unittest
from anvil import log
class TestLog(unittest.TestCase):
def setUp(self):
super(TestLog, self).setUp()
self.test_logger = log.getLogger().logger
self.test_logger.handlers = []
self.log_name = tempfile.mkstemp()[1]
def tearDown(self):
super(TestLog, self).tearDown()
if os.path.isfile(self.log_name):
os.remove(self.log_name)
def test_logger_has_two_handlers(self):
log.setupLogging(log.INFO, log_name=self.log_name)
self.assertEqual(len(self.test_logger.handlers), 2)

4
smithy
View File

@ -371,8 +371,10 @@ for i in $BOOT_FILES; do
done
mkdir -p -v /etc/anvil /usr/share/anvil
touch /var/log/anvil.log
if [ -n "$SUDO_UID" -a -n "SUDO_GID" ]; then
chown -c "$SUDO_UID:$SUDO_GID" /etc/anvil /usr/share/anvil
chown -c "$SUDO_UID:$SUDO_GID" /etc/anvil /usr/share/anvil \
/var/log/anvil.log
[ -d .bootstrap ] && chown -R "$SUDO_UID:$SUDO_GID" .bootstrap
fi