Add new LOG class

pull/1095/head
Matthew D. Scholefield 2017-09-18 13:55:58 -05:00
parent e182abedea
commit cfdc405da5
45 changed files with 281 additions and 251 deletions

View File

@ -9,11 +9,8 @@ from speech_recognition import AudioSource
from mycroft.client.speech.listener import RecognizerLoop
from mycroft.client.speech.mic import ResponsiveRecognizer
from mycroft.client.speech.mic import logger as speech_logger
from mycroft.util.log import getLogger
__author__ = 'wolfgange3311999'
logger = getLogger('audio_test_runner')
def to_percent(val):
@ -79,7 +76,6 @@ class AudioTester(object):
samp_rate, 'en-us')
self.listener = ResponsiveRecognizer(self.ww_recognizer)
print
speech_logger.setLevel(100) # Disables logging to clean output
def test_audio(self, file_name):
source = FileMockMicrophone(file_name)

View File

@ -27,7 +27,7 @@ import subprocess
from mycroft.configuration import ConfigurationManager
from mycroft.messagebus.client.ws import WebsocketClient
from mycroft.messagebus.message import Message
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
import mycroft.audio.speech as speech
try:
@ -39,7 +39,6 @@ __author__ = 'forslund'
MainModule = '__init__'
sys.path.append(abspath(dirname(__file__)))
logger = getLogger("Audio")
ws = None
@ -75,7 +74,7 @@ def get_services(services_folder):
Returns:
Sorted list of audio services.
"""
logger.info("Loading skills from " + services_folder)
LOG.info("Loading skills from " + services_folder)
services = []
possible_services = listdir(services_folder)
for i in possible_services:
@ -90,7 +89,7 @@ def get_services(services_folder):
try:
services.append(create_service_descriptor(name))
except:
logger.error('Failed to create service from ' + name,
LOG.error('Failed to create service from ' + name,
exc_info=True)
if (not isdir(location) or
not MainModule + ".py" in listdir(location)):
@ -98,7 +97,7 @@ def get_services(services_folder):
try:
services.append(create_service_descriptor(location))
except:
logger.error('Failed to create service from ' + name,
LOG.error('Failed to create service from ' + name,
exc_info=True)
return sorted(services, key=lambda p: p.get('name'))
@ -114,18 +113,18 @@ def load_services(config, ws, path=None):
Returns:
List of started services.
"""
logger.info("Loading services")
LOG.info("Loading services")
if path is None:
path = dirname(abspath(__file__)) + '/services/'
service_directories = get_services(path)
service = []
for descriptor in service_directories:
logger.info('Loading ' + descriptor['name'])
LOG.info('Loading ' + descriptor['name'])
try:
service_module = imp.load_module(descriptor["name"] + MainModule,
*descriptor["info"])
except:
logger.error('Failed to import module ' + descriptor['name'],
LOG.error('Failed to import module ' + descriptor['name'],
exc_info=True)
if (hasattr(service_module, 'autodetect') and
callable(service_module.autodetect)):
@ -133,14 +132,14 @@ def load_services(config, ws, path=None):
s = service_module.autodetect(config, ws)
service += s
except:
logger.error('Failed to autodetect...',
LOG.error('Failed to autodetect...',
exc_info=True)
if (hasattr(service_module, 'load_service')):
try:
s = service_module.load_service(config, ws)
service += s
except:
logger.error('Failed to load service...',
LOG.error('Failed to load service...',
exc_info=True)
return service
@ -157,19 +156,19 @@ def load_services_callback():
config = ConfigurationManager.get().get("Audio")
service = load_services(config, ws)
logger.info(service)
LOG.info(service)
default_name = config.get('default-backend', '')
logger.info('Finding default backend...')
LOG.info('Finding default backend...')
for s in service:
logger.info('checking ' + s.name)
LOG.info('checking ' + s.name)
if s.name == default_name:
default = s
logger.info('Found ' + default.name)
LOG.info('Found ' + default.name)
break
else:
default = None
logger.info('no default found')
logger.info('Default:' + str(default))
LOG.info('no default found')
LOG.info('Default:' + str(default))
ws.on('mycroft.audio.service.play', _play)
ws.on('mycroft.audio.service.pause', _pause)
@ -244,11 +243,11 @@ def _stop(message=None):
message: message bus message, not used but required
"""
global current
logger.info('stopping all playing services')
LOG.info('stopping all playing services')
if current:
current.stop()
current = None
logger.info('Stopped')
LOG.info('Stopped')
def _lower_volume(message):
@ -260,7 +259,7 @@ def _lower_volume(message):
"""
global current
global volume_is_low
logger.info('lowering volume')
LOG.info('lowering volume')
if current:
current.lower_volume()
volume_is_low = True
@ -268,7 +267,7 @@ def _lower_volume(message):
if pulse_quiet:
pulse_quiet()
except Exception as e:
logger.error(e)
LOG.error(e)
muted_sinks = []
@ -330,12 +329,12 @@ def _restore_volume(message):
"""
global current
global volume_is_low
logger.info('maybe restoring volume')
LOG.info('maybe restoring volume')
if current:
volume_is_low = False
time.sleep(2)
if not volume_is_low:
logger.info('restoring volume')
LOG.info('restoring volume')
current.restore_volume()
if pulse_restore:
pulse_restore()
@ -352,31 +351,31 @@ def play(tracks, prefered_service):
the tracks.
"""
global current
logger.info('play')
LOG.info('play')
_stop()
uri_type = tracks[0].split(':')[0]
logger.info('uri_type: ' + uri_type)
LOG.info('uri_type: ' + uri_type)
# check if user requested a particular service
if prefered_service and uri_type in prefered_service.supported_uris():
service = prefered_service
# check if default supports the uri
elif default and uri_type in default.supported_uris():
logger.info("Using default backend")
logger.info(default.name)
LOG.info("Using default backend")
LOG.info(default.name)
service = default
else: # Check if any other service can play the media
for s in service:
logger.info(str(s))
LOG.info(str(s))
if uri_type in s.supported_uris():
service = s
break
else:
return
logger.info('Clear list')
LOG.info('Clear list')
service.clear_list()
logger.info('Add tracks' + str(tracks))
LOG.info('Add tracks' + str(tracks))
service.add_list(tracks)
logger.info('Playing')
LOG.info('Playing')
service.play()
current = service
@ -390,17 +389,17 @@ def _play(message):
message: message bus message, not used but required
"""
global service
logger.info('mycroft.audio.service.play')
logger.info(message.data['tracks'])
LOG.info('mycroft.audio.service.play')
LOG.info(message.data['tracks'])
tracks = message.data['tracks']
# Find if the user wants to use a specific backend
for s in service:
logger.info(s.name)
LOG.info(s.name)
if s.name in message.data['utterance']:
prefered_service = s
logger.info(s.name + ' would be prefered')
LOG.info(s.name + ' would be prefered')
break
else:
prefered_service = None
@ -467,15 +466,15 @@ def main():
message = json.dumps(_message)
except:
pass
logger.debug(message)
LOG.debug(message)
logger.info("Staring Audio Services")
LOG.info("Staring Audio Services")
ws.on('message', echo)
ws.once('open', load_services_callback)
try:
ws.run_forever()
except KeyboardInterrupt, e:
logger.exception(e)
LOG.exception(e)
speech.shutdown()
sys.exit()

View File

@ -1,5 +1,5 @@
from mycroft.messagebus.message import Message
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.audio.services import AudioBackend
from os.path import dirname, abspath, basename
import sys
@ -8,16 +8,15 @@ from mimetypes import guess_type
import pychromecast
logger = getLogger(abspath(__file__).split('/')[-2])
__author__ = 'forslund'
class ChromecastService(AudioBackend):
def _connect(self, message):
logger.info('Trying to connect to chromecast')
LOG.info('Trying to connect to chromecast')
casts = pychromecast.get_chromecasts()
if self.config is None or 'identifier' not in self.config:
logger.error("Chromecast identifier not found!")
LOG.error("Chromecast identifier not found!")
return # Can't connect since no id is specified
else:
identifier = self.config['identifier']
@ -26,7 +25,7 @@ class ChromecastService(AudioBackend):
self.cast = c
break
else:
logger.info('Couldn\'t find chromecast ' + identifier)
LOG.info('Couldn\'t find chromecast ' + identifier)
self.connection_attempts += 1
time.sleep(10)
self.emitter.emit(Message('ChromecastServiceConnect'))
@ -118,7 +117,7 @@ def autodetect(config, emitter):
casts = pychromecast.get_chromecasts()
ret = []
for c in casts:
logger.info(c.name + " found.")
LOG.info(c.name + " found.")
ret.append(ChromecastService(config, emitter, c.name.lower(), c))
return ret

View File

@ -1,11 +1,10 @@
from mycroft.messagebus.message import Message
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.audio.services import AudioBackend
from os.path import dirname, abspath, basename
import sys
import time
logger = getLogger(abspath(__file__).split('/')[-2])
__author__ = 'forslund'
sys.path.append(abspath(dirname(__file__)))
@ -25,13 +24,13 @@ class MopidyService(AudioBackend):
self.mopidy = Mopidy(url)
except:
if self.connection_attempts < 1:
logger.debug('Could not connect to server, will retry quietly')
LOG.debug('Could not connect to server, will retry quietly')
self.connection_attempts += 1
time.sleep(10)
self.emitter.emit(Message('MopidyServiceConnect'))
return
logger.info('Connected to mopidy server')
LOG.info('Connected to mopidy server')
def __init__(self, config, emitter, name='mopidy'):
self.connection_attempts = 0

View File

@ -2,14 +2,13 @@ import subprocess
from time import sleep
from mycroft.audio.services import AudioBackend
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.messagebus.message import Message
from os.path import abspath
__author__ = 'forslund'
logger = getLogger(abspath(__file__).split('/')[-2])
class Mpg123Service(AudioBackend):
@ -35,14 +34,14 @@ class Mpg123Service(AudioBackend):
def add_list(self, tracks):
self.tracks = tracks
logger.info("Track list is " + str(tracks))
LOG.info("Track list is " + str(tracks))
def _play(self, message=None):
""" Implementation specific async method to handle playback.
This allows mpg123 service to use the "next method as well
as basic play/stop.
"""
logger.info('Mpg123Service._play')
LOG.info('Mpg123Service._play')
self._is_playing = True
track = self.tracks[self.index]
@ -68,12 +67,12 @@ class Mpg123Service(AudioBackend):
self._is_playing = False
def play(self):
logger.info('Call Mpg123ServicePlay')
LOG.info('Call Mpg123ServicePlay')
self.index = 0
self.emitter.emit(Message('Mpg123ServicePlay'))
def stop(self):
logger.info('Mpg123ServiceStop')
LOG.info('Mpg123ServiceStop')
self._stop_signal = True
while self._is_playing:
sleep(0.1)

View File

@ -1,9 +1,8 @@
from os.path import dirname, abspath, basename
from mycroft.audio.services import AudioBackend
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
import vlc
logger = getLogger(abspath(__file__).split('/')[-2])
class VlcService(AudioBackend):
@ -26,18 +25,18 @@ class VlcService(AudioBackend):
self.list_player.set_media_list(empty)
def add_list(self, tracks):
logger.info("Track list is " + str(tracks))
LOG.info("Track list is " + str(tracks))
vlc_tracks = self.instance.media_list_new()
for t in tracks:
vlc_tracks.add_media(self.instance.media_new(t))
self.list_player.set_media_list(vlc_tracks)
def play(self):
logger.info('VLCService Play')
LOG.info('VLCService Play')
self.list_player.play()
def stop(self):
logger.info('VLCService Stop')
LOG.info('VLCService Stop')
self.clear_list()
self.list_player.stop()

View File

@ -3,13 +3,12 @@ from mycroft.util import create_signal, stop_speaking, check_for_signal
from mycroft.lock import Lock as PIDLock # Create/Support PID locking file
from mycroft.configuration import ConfigurationManager
from mycroft.messagebus.message import Message
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from threading import Lock
import time
import re
logger = getLogger("Audio speech")
ws = None
config = None
@ -60,7 +59,7 @@ def handle_speak(event):
except KeyboardInterrupt:
raise
except:
logger.error('Error in mute_and_speak', exc_info=True)
LOG.error('Error in mute_and_speak', exc_info=True)
if _last_stop_signal > start or check_for_signal('buttonPress'):
break
else:
@ -88,7 +87,7 @@ def mute_and_speak(utterance):
tts.init(ws)
tts_hash = hash(str(config.get('tts', '')))
logger.info("Speak: " + utterance)
LOG.info("Speak: " + utterance)
try:
tts.execute(utterance)
finally:

View File

@ -35,14 +35,13 @@ from mycroft.messagebus.message import Message
from mycroft.util import play_wav, create_signal, connected, \
wait_while_speaking
from mycroft.util.audio_test import record
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.client.enclosure.display_manager import \
initiate_display_manager_ws
from mycroft.api import is_paired, has_been_paired
__author__ = 'aatchison', 'jdorleans', 'iward'
LOG = getLogger("EnclosureClient")
class EnclosureReader(Thread):

View File

@ -17,12 +17,11 @@
import mycroft.client.enclosure.display_manager as DisplayManager
from mycroft.messagebus.message import Message
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from PIL import Image
__author__ = 'jdorleans'
LOGGER = getLogger(__name__)
'''

View File

@ -16,11 +16,10 @@
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'jdorleans'
LOGGER = getLogger(__name__)
class EnclosureArduino:

View File

@ -17,18 +17,14 @@
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread, Timer
from mycroft.messagebus.client.ws import WebsocketClient
from mycroft.configuration import ConfigurationManager
from mycroft.util import get_ipc_directory
import json
import os
from logging import getLogger
from mycroft.util.log import LOG
__author__ = 'connorpenrod', 'michaelnguyen'
LOG = getLogger("Display Manager (mycroft.client.enclosure)")
def _write_data(dictionary):
"""Writes the parama as JSON to the
IPC dir (/tmp/mycroft/ipc/managers)

View File

@ -16,11 +16,10 @@
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'jdorleans'
LOGGER = getLogger(__name__)
class EnclosureEyes:

View File

@ -16,13 +16,12 @@
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from threading import Timer
import time
__author__ = 'jdorleans'
LOG = getLogger(__name__)
class EnclosureMouth:

View File

@ -16,11 +16,10 @@
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'iward'
LOGGER = getLogger(__name__)
class EnclosureWeather:

View File

@ -16,7 +16,7 @@
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from mycroft.configuration import ConfigurationManager
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from os.path import dirname, exists, join, abspath
import os
import time
@ -24,7 +24,6 @@ import tempfile
__author__ = 'seanfitz, jdorleans, jarbas'
LOG = getLogger("HotwordFactory")
RECOGNIZER_DIR = join(abspath(dirname(__file__)), "recognizer")

View File

@ -31,10 +31,9 @@ from mycroft.configuration import ConfigurationManager
from mycroft.metrics import MetricsAggregator
from mycroft.session import SessionManager
from mycroft.stt import STTFactory
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.client.speech.hotword_factory import HotWordFactory
LOG = getLogger(__name__)
class AudioProducer(Thread):
@ -135,7 +134,7 @@ class AudioConsumer(Thread):
self.emitter.emit("recognizer_loop:wakeword", payload)
if self._audio_length(audio) < self.MIN_AUDIO_SIZE:
LOG.warn("Audio too short to be processed")
LOG.warning("Audio too short to be processed")
else:
self.transcribe(audio)
@ -153,7 +152,7 @@ class AudioConsumer(Thread):
except HTTPError as e:
if e.response.status_code == 401:
text = "pair my device" # phrase to start the pairing process
LOG.warn("Access Denied at mycroft.ai")
LOG.warning("Access Denied at mycroft.ai")
except Exception as e:
LOG.error(e)
LOG.error("Speech Recognition could not understand audio")

View File

@ -26,10 +26,9 @@ from mycroft.configuration import ConfigurationManager
from mycroft.identity import IdentityManager
from mycroft.messagebus.client.ws import WebsocketClient
from mycroft.messagebus.message import Message
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.lock import Lock as PIDLock # Create/Support PID locking file
logger = getLogger("SpeechClient")
ws = None
lock = Lock()
loop = None
@ -38,27 +37,27 @@ config = ConfigurationManager.get()
def handle_record_begin():
logger.info("Begin Recording...")
LOG.info("Begin Recording...")
ws.emit(Message('recognizer_loop:record_begin'))
def handle_record_end():
logger.info("End Recording...")
LOG.info("End Recording...")
ws.emit(Message('recognizer_loop:record_end'))
def handle_no_internet():
logger.debug("Notifying enclosure of no internet connection")
LOG.debug("Notifying enclosure of no internet connection")
ws.emit(Message('enclosure.notify.no_internet'))
def handle_wakeword(event):
logger.info("Wakeword Detected: " + event['utterance'])
LOG.info("Wakeword Detected: " + event['utterance'])
ws.emit(Message('recognizer_loop:wakeword', event))
def handle_utterance(event):
logger.info("Utterance: " + str(event['utterances']))
LOG.info("Utterance: " + str(event['utterances']))
ws.emit(Message('recognizer_loop:utterance', event))
@ -70,7 +69,7 @@ def handle_speak(event):
def handle_complete_intent_failure(event):
logger.info("Failed to find intent.")
LOG.info("Failed to find intent.")
# TODO: Localize
data = {'utterance':
"Sorry, I didn't catch that. Please rephrase your request."}
@ -161,7 +160,7 @@ def main():
try:
loop.run()
except KeyboardInterrupt, e:
logger.exception(e)
LOG.exception(e)
sys.exit()

View File

@ -44,9 +44,8 @@ from mycroft.util import (
resolve_resource_file,
play_wav
)
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
logger = getLogger(__name__)
__author__ = 'seanfitz'
@ -81,7 +80,7 @@ class MutableStream(object):
return self.muted_buffer
input_latency = self.wrapped_stream.get_input_latency()
if input_latency > 0.2:
logger.warn("High input latency: %f" % input_latency)
LOG.warning("High input latency: %f" % input_latency)
audio = b"".join(list(frames))
return audio
@ -308,7 +307,7 @@ class ResponsiveRecognizer(speech_recognition.Recognizer):
if check_for_signal('buttonPress'):
# Signal is still here, assume it was intended to
# begin recording
logger.debug("Button Pressed, wakeword not needed")
LOG.debug("Button Pressed, wakeword not needed")
return True
return False
@ -336,7 +335,7 @@ class ResponsiveRecognizer(speech_recognition.Recognizer):
try:
self.filenames_to_upload.append(filename)
for i, fn in enumerate(self.filenames_to_upload):
logger.debug('Uploading ' + fn + '...')
LOG.debug('Uploading ' + fn + '...')
os.chmod(fn, 0o666)
cmd = 'scp -o StrictHostKeyChecking=no -P ' + \
str(self.upload_config['port']) + ' -i ' + \
@ -345,7 +344,7 @@ class ResponsiveRecognizer(speech_recognition.Recognizer):
del self.filenames_to_upload[i]
os.remove(fn)
else:
logger.debug('Could not upload ' + fn + ' to ' + server)
LOG.debug('Could not upload ' + fn + ' to ' + server)
finally:
self.upload_lock.release()
@ -489,12 +488,12 @@ class ResponsiveRecognizer(speech_recognition.Recognizer):
# speech is detected, but there is no code to actually do that.
self.adjust_for_ambient_noise(source, 1.0)
logger.debug("Waiting for wake word...")
LOG.debug("Waiting for wake word...")
self._wait_until_wake_word(source, sec_per_buffer)
if self._stop_signaled:
return
logger.debug("Recording...")
LOG.debug("Recording...")
emitter.emit("recognizer_loop:record_begin")
# If enabled, play a wave file with a short sound to audibly
@ -509,12 +508,12 @@ class ResponsiveRecognizer(speech_recognition.Recognizer):
audio_data = self._create_audio_data(frame_data, source)
emitter.emit("recognizer_loop:record_end")
if self.save_utterances:
logger.info("Recording utterance")
LOG.info("Recording utterance")
stamp = str(datetime.datetime.now())
filename = "/tmp/mycroft_utterance%s.wav" % stamp
with open(filename, 'wb') as filea:
filea.write(audio_data.get_wav_data())
logger.debug("Thinking...")
LOG.debug("Thinking...")
return audio_data

View File

@ -38,12 +38,11 @@ from threading import Thread, Lock # nopep8
from mycroft.messagebus.client.ws import WebsocketClient # nopep8
from mycroft.messagebus.message import Message # nopep8
from mycroft.util import get_ipc_directory # nopep8
from mycroft.util.log import getLogger # nopep8
from mycroft.util.log import LOG # nopep8
from mycroft.configuration import ConfigurationManager # nopep8
ws = None
mutex = Lock()
logger = getLogger("CLIClient")
utterances = []
chat = [] # chat history, oldest at the lowest index
@ -855,7 +854,7 @@ def gui_main(stdscr):
# User hit Ctrl+C to quit
pass
except KeyboardInterrupt, e:
logger.exception(e)
LOG.exception(e)
finally:
scr.erase()
scr.refresh()
@ -883,7 +882,7 @@ def simple_cli():
# User hit Ctrl+C to quit
print("")
except KeyboardInterrupt, e:
logger.exception(e)
LOG.exception(e)
event_thread.exit()
sys.exit()

View File

@ -49,11 +49,10 @@ from mycroft.messagebus.client.ws import WebsocketClient
from mycroft.messagebus.message import Message
from mycroft.util import connected, wait_while_speaking, is_speaking, \
stop_speaking
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'aatchison and penrods'
LOG = getLogger("WiFiClient")
SCRIPT_DIR = dirname(realpath(__file__))
@ -480,7 +479,7 @@ class WiFi:
connected = self.is_connected(ssid)
if connected:
LOG.warn("Mycroft is already connected to %s" % ssid)
LOG.warning("Mycroft is already connected to %s" % ssid)
else:
self.disconnect()
LOG.info("Connecting to: %s" % ssid)

View File

@ -21,12 +21,11 @@ import re
from genericpath import exists, isfile
from os.path import join, dirname, expanduser
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.util.json_helper import load_commented_json
__author__ = 'seanfitz, jdorleans'
LOG = getLogger(__name__)
DEFAULT_CONFIG = join(dirname(__file__), 'mycroft.conf')
SYSTEM_CONFIG = '/etc/mycroft/mycroft.conf'
@ -158,7 +157,7 @@ class RemoteConfiguration(object):
RemoteConfiguration.__load(config, setting)
RemoteConfiguration.__store_cache(setting)
except Exception as e:
LOG.warn("Failed to fetch remote configuration: %s" % repr(e))
LOG.warning("Failed to fetch remote configuration: %s" % repr(e))
RemoteConfiguration.__load_cache(config)
else:

View File

@ -21,9 +21,9 @@ from io import open
import os
import random
from mycroft.util import log, resolve_resource_file
from mycroft.util.log import LOG
__author__ = 'seanfitz'
logger = log.getLogger(__name__)
__doc__ = """
@ -98,7 +98,7 @@ class DialogLoader(object):
a loaded instance of a dialog renderer
"""
if not os.path.exists(dialog_dir) or not os.path.isdir(dialog_dir):
logger.warn("No dialog found: " + dialog_dir)
LOG.warning("No dialog found: " + dialog_dir)
return self.__renderer
for f in sorted(
@ -133,7 +133,7 @@ def get(phrase, lang=None, context=None):
filename = "text/"+lang.lower()+"/"+phrase+".dialog"
template = resolve_resource_file(filename)
if not template:
logger.debug("Resource file not found: " + filename)
LOG.debug("Resource file not found: " + filename)
return phrase
stache = MustacheDialogRenderer()

View File

@ -26,11 +26,10 @@ from websocket import WebSocketApp
from mycroft.configuration import ConfigurationManager
from mycroft.messagebus.message import Message
from mycroft.util import validate_param
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'seanfitz', 'jdorleans'
LOG = getLogger(__name__)
class WebsocketClient(object):
@ -75,7 +74,7 @@ class WebsocketClient(object):
self.client.close()
except Exception, e:
LOG.error(repr(e))
LOG.warn("WS Client will reconnect in %d seconds." % self.retry)
LOG.warning("WS Client will reconnect in %d seconds." % self.retry)
time.sleep(self.retry)
self.retry = min(self.retry * 2, 60)
self.client = self.create_client()

View File

@ -23,10 +23,9 @@ import traceback
import tornado.websocket
from pyee import EventEmitter
import mycroft.util.log
from mycroft.util.log import LOG
from mycroft.messagebus.message import Message
logger = mycroft.util.log.getLogger(__name__)
__author__ = 'seanfitz'
EventBusEmitter = EventEmitter()
@ -44,7 +43,7 @@ class WebsocketEventHandler(tornado.websocket.WebSocketHandler):
self.emitter.on(event_name, handler)
def on_message(self, message):
logger.debug(message)
LOG.debug(message)
try:
deserialized_message = Message.deserialize(message)
except:
@ -53,7 +52,7 @@ class WebsocketEventHandler(tornado.websocket.WebSocketHandler):
try:
self.emitter.emit(deserialized_message.type, deserialized_message)
except Exception, e:
logger.exception(e)
LOG.exception(e)
traceback.print_exc(file=sys.stdout)
pass

View File

@ -24,10 +24,9 @@ import requests
from mycroft.configuration import ConfigurationManager
from mycroft.session import SessionManager
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.util.setup_base import get_version
LOG = getLogger("Metrics")
config = ConfigurationManager.get().get('server')

View File

@ -21,10 +21,9 @@ from threading import Lock
from uuid import uuid4
from mycroft.configuration import ConfigurationManager
from mycroft.util import log
from mycroft.util.log import LOG
__author__ = 'seanfitz'
logger = log.getLogger(__name__)
config = ConfigurationManager.get().get('session')
@ -77,7 +76,7 @@ class SessionManager(object):
SessionManager.__current_session.expired()):
SessionManager.__current_session = Session(
str(uuid4()), expiration_seconds=config.get('ttl', 180))
logger.info(
LOG.info(
"New Session Start: " +
SessionManager.__current_session.session_id)
return SessionManager.__current_session

View File

@ -24,11 +24,10 @@ from mycroft.configuration import ConfigurationManager
from mycroft.messagebus.client.ws import WebsocketClient
from mycroft.skills.core import create_skill_descriptor, load_skill
from mycroft.skills.intent_service import IntentService
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'seanfitz'
LOG = getLogger("SkillContainer")
class SkillContainer(object):

View File

@ -33,7 +33,7 @@ from mycroft.configuration import ConfigurationManager
from mycroft.dialog import DialogLoader
from mycroft.filesystem import FileSystemAccess
from mycroft.messagebus.message import Message
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.skills.settings import SkillSettings
from inspect import getargspec
@ -43,7 +43,6 @@ __author__ = 'seanfitz'
MainModule = '__init__'
logger = getLogger(__name__)
def load_vocab_from_file(path, vocab_type, emitter):
@ -122,10 +121,10 @@ def load_skill(skill_descriptor, emitter, skill_id, BLACKLISTED_SKILLS=None):
"""
BLACKLISTED_SKILLS = BLACKLISTED_SKILLS or []
try:
logger.info("ATTEMPTING TO LOAD SKILL: " + skill_descriptor["name"] +
LOG.info("ATTEMPTING TO LOAD SKILL: " + skill_descriptor["name"] +
" with ID " + str(skill_id))
if skill_descriptor['name'] in BLACKLISTED_SKILLS:
logger.info("SKILL IS BLACKLISTED " + skill_descriptor["name"])
LOG.info("SKILL IS BLACKLISTED " + skill_descriptor["name"])
return None
skill_module = imp.load_module(
skill_descriptor["name"] + MainModule, *skill_descriptor["info"])
@ -139,14 +138,14 @@ def load_skill(skill_descriptor, emitter, skill_id, BLACKLISTED_SKILLS=None):
# Set up intent handlers
skill.initialize()
skill._register_decorated()
logger.info("Loaded " + skill_descriptor["name"])
LOG.info("Loaded " + skill_descriptor["name"])
return skill
else:
logger.warn(
LOG.warning(
"Module %s does not appear to be skill" % (
skill_descriptor["name"]))
except:
logger.error(
LOG.error(
"Failed to load skill: " + skill_descriptor["name"], exc_info=True)
return None
@ -222,7 +221,7 @@ class MycroftSkill(object):
self.vocab_dir = None
self.file_system = FileSystemAccess(join('skills', self.name))
self.registered_intents = []
self.log = getLogger(self.name)
self.log = LOG.create_logger(self.name)
self.reload_skill = True
self.events = []
self.skill_id = 0
@ -287,7 +286,7 @@ class MycroftSkill(object):
Usually used to create intents rules and register them.
"""
logger.debug("No initialize function implemented")
LOG.debug("No initialize function implemented")
def converse(self, utterances, lang="en-us"):
"""
@ -364,7 +363,7 @@ class MycroftSkill(object):
self.speak(
"An error occurred while processing a request in " +
self.name)
logger.error(
LOG.error(
"An error occurred while processing a request in " +
self.name, exc_info=True)
# indicate completion with exception
@ -420,7 +419,7 @@ class MycroftSkill(object):
def disable_intent(self, intent_name):
"""Disable a registered intent"""
logger.debug('Disabling intent ' + intent_name)
LOG.debug('Disabling intent ' + intent_name)
name = str(self.skill_id) + ':' + intent_name
self.emitter.emit(Message("detach_intent", {"intent_name": name}))
@ -431,10 +430,10 @@ class MycroftSkill(object):
self.registered_intents.remove((name, intent))
intent.name = name
self.register_intent(intent, None)
logger.debug('Enabling intent ' + intent_name)
LOG.debug('Enabling intent ' + intent_name)
break
else:
logger.error('Could not enable ' + intent_name +
LOG.error('Could not enable ' + intent_name +
', it hasn\'t been registered.')
def set_context(self, context, word=''):
@ -510,7 +509,7 @@ class MycroftSkill(object):
if exists(dialog_dir):
self.dialog_renderer = DialogLoader().load(dialog_dir)
else:
logger.debug('No dialog loaded, ' + dialog_dir + ' does not exist')
LOG.debug('No dialog loaded, ' + dialog_dir + ' does not exist')
def load_data_files(self, root_directory):
self.init_dialog(root_directory)
@ -524,7 +523,7 @@ class MycroftSkill(object):
if exists(vocab_dir):
load_vocabulary(vocab_dir, self.emitter)
else:
logger.debug('No vocab loaded, ' + vocab_dir + ' does not exist')
LOG.debug('No vocab loaded, ' + vocab_dir + ' does not exist')
def load_regex_files(self, regex_dir):
load_regex(regex_dir, self.emitter)
@ -538,7 +537,7 @@ class MycroftSkill(object):
try:
self.stop()
except:
logger.error("Failed to stop skill: {}".format(self.name),
LOG.error("Failed to stop skill: {}".format(self.name),
exc_info=True)
@abc.abstractmethod
@ -568,7 +567,7 @@ class MycroftSkill(object):
try:
self.stop()
except:
logger.error("Failed to stop skill: {}".format(self.name),
LOG.error("Failed to stop skill: {}".format(self.name),
exc_info=True)
def _schedule_event(self, handler, when, data=None, name=None,
@ -672,9 +671,9 @@ class FallbackSkill(MycroftSkill):
if handler(message):
return
except Exception as e:
logger.info('Exception in fallback: ' + str(e))
LOG.info('Exception in fallback: ' + str(e))
ws.emit(Message('complete_intent_failure'))
logger.warn('No fallback could handle intent.')
LOG.warning('No fallback could handle intent.')
return handler
@ -713,7 +712,7 @@ class FallbackSkill(MycroftSkill):
if handler == handler_to_del:
del cls.fallback_handlers[priority]
return
logger.warn('Could not remove fallback!')
LOG.warning('Could not remove fallback!')
def remove_instance_handlers(self):
"""

View File

@ -1,5 +1,5 @@
from mycroft.messagebus.message import Message
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from threading import Thread
from Queue import Queue
@ -8,7 +8,6 @@ import json
from os.path import isfile
logger = getLogger(__name__)
class EventScheduler(Thread):
@ -41,7 +40,7 @@ class EventScheduler(Thread):
try:
json_data = json.load(f)
except Exception as e:
logger.error(e)
LOG.error(e)
current_time = time.time()
for key in json_data:
event_list = json_data[key]
@ -132,9 +131,9 @@ class EventScheduler(Thread):
if event and sched_time:
self.schedule_event(event, sched_time, repeat, data)
elif not event:
logger.error('Scheduled event name not provided')
LOG.error('Scheduled event name not provided')
else:
logger.error('Scheduled event time not provided')
LOG.error('Scheduled event time not provided')
def remove_event(self, event):
""" Remove event using thread safe queue. """

View File

@ -20,7 +20,7 @@ from adapt.engine import IntentDeterminationEngine
from mycroft.messagebus.message import Message
from mycroft.skills.core import open_intent_envelope
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.util.parse import normalize
from mycroft.configuration import ConfigurationManager
@ -29,7 +29,6 @@ import time
__author__ = 'seanfitz'
logger = getLogger(__name__)
class ContextManager(object):
@ -240,7 +239,7 @@ class IntentService(object):
# TODO - Should Adapt handle this?
best_intent['utterance'] = utterance
except StopIteration, e:
logger.exception(e)
LOG.exception(e)
continue
if best_intent and best_intent.get('confidence', 0.0) > 0.0:
@ -270,10 +269,9 @@ class IntentService(object):
start_concept, end_concept, alias_of=alias_of)
def handle_register_intent(self, message):
print "registring " + str(message.data)
print "Registering: " + str(message.data)
intent = open_intent_envelope(message)
self.engine.register_intent_parser(intent)
print "Done"
def handle_detach_intent(self, message):
intent_name = message.data.get('intent_name')

View File

@ -35,11 +35,10 @@ from mycroft.skills.intent_service import IntentService
from mycroft.skills.padatious_service import PadatiousService
from mycroft.skills.event_scheduler import EventScheduler
from mycroft.util import connected
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.api import is_paired
import mycroft.dialog
logger = getLogger("Skills")
__author__ = 'seanfitz'
@ -82,17 +81,17 @@ def install_default_skills(speak=True):
# 'utterance': mycroft.dialog.get("skills updated")}))
pass
elif not connected():
logger.error('msm failed, network connection is not available')
LOG.error('msm failed, network connection is not available')
ws.emit(Message("speak", {
'utterance': mycroft.dialog.get("no network connection")}))
elif res != 0:
logger.error('msm failed with error {}: {}'.format(res, output))
LOG.error('msm failed with error {}: {}'.format(res, output))
ws.emit(Message("speak", {
'utterance': mycroft.dialog.get(
"sorry I couldn't install default skills")}))
else:
logger.error("Unable to invoke Mycroft Skill Manager: " + MSM_BIN)
LOG.error("Unable to invoke Mycroft Skill Manager: " + MSM_BIN)
def skills_manager(message):
@ -106,7 +105,7 @@ def skills_manager(message):
if skills_manager_timer is None:
pass
# Install default skills and look for updates via Github
logger.debug("==== Invoking Mycroft Skill Manager: " + MSM_BIN)
LOG.debug("==== Invoking Mycroft Skill Manager: " + MSM_BIN)
install_default_skills(False)
# Perform check again once and hour
@ -288,14 +287,14 @@ class WatchSkills(Thread):
# checking if skill should be reloaded
if not skill["instance"].reload_skill:
continue
logger.debug("Reloading Skill: " + skill_folder)
LOG.debug("Reloading Skill: " + skill_folder)
# removing listeners and stopping threads
skill["instance"].shutdown()
# -2 since two local references that are known
refs = sys.getrefcount(skill["instance"]) - 2
if refs > 0:
logger.warn(
LOG.warning(
"After shutdown of {} there are still "
"{} references remaining. The skill "
"won't be cleaned from memory."
@ -353,7 +352,7 @@ def handle_converse_request(message):
try:
instance = loaded_skills[skill]["instance"]
except:
logger.error("converse requested but skill not loaded")
LOG.error("converse requested but skill not loaded")
ws.emit(Message("skill.converse.response", {
"skill_id": 0, "result": False}))
return
@ -363,7 +362,7 @@ def handle_converse_request(message):
"skill_id": skill_id, "result": result}))
return
except:
logger.error(
LOG.error(
"Converse method malformed for skill " + str(skill_id))
ws.emit(Message("skill.converse.response",
{"skill_id": 0, "result": False}))
@ -393,7 +392,7 @@ def main():
message = json.dumps(_message)
except:
pass
logger.debug(message)
LOG('SKILLS').debug(message)
ws.on('message', _echo)
ws.on('skill.converse.request', handle_converse_request)

View File

@ -24,12 +24,11 @@ from pkg_resources import get_distribution
from mycroft.configuration import ConfigurationManager
from mycroft.messagebus.message import Message
from mycroft.skills.core import FallbackSkill
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.util.parse import normalize
__author__ = 'matthewscholefield'
logger = getLogger(__name__)
PADATIOUS_VERSION = '0.2.2' # Also update in requirements.txt
@ -43,7 +42,7 @@ class PadatiousService(FallbackSkill):
try:
from padatious import IntentContainer
except ImportError:
logger.error('Padatious not installed. Please re-run dev_setup.sh')
LOG.error('Padatious not installed. Please re-run dev_setup.sh')
try:
call(['notify-send', 'Padatious not installed',
'Please run build_host_setup and dev_setup again'])
@ -51,9 +50,9 @@ class PadatiousService(FallbackSkill):
pass
return
ver = get_distribution('padatious').version
logger.warning('VERSION: ' + ver)
LOG.warning('VERSION: ' + ver)
if ver != PADATIOUS_VERSION:
logger.warning('Using Padatious v' + ver + '. Please re-run ' +
LOG.warning('Using Padatious v' + ver + '. Please re-run ' +
'dev_setup.sh to install ' + PADATIOUS_VERSION)
self.container = IntentContainer(intent_cache)
@ -76,13 +75,13 @@ class PadatiousService(FallbackSkill):
self.train_time = -1.0
self.finished_training_event.clear()
logger.info('Training...')
LOG.info('Training...')
self.container.train(print_updates=False)
logger.info('Training complete.')
LOG.info('Training complete.')
self.finished_training_event.set()
def register_intent(self, message):
logger.debug('Registering Padatious intent: ' +
LOG.debug('Registering Padatious intent: ' +
message.data['intent_name'])
file_name = message.data['file_name']
@ -96,12 +95,12 @@ class PadatiousService(FallbackSkill):
def handle_fallback(self, message):
utt = message.data.get('utterance')
logger.debug("Padatious fallback attempt: " + utt)
LOG.debug("Padatious fallback attempt: " + utt)
utt = normalize(utt, message.data.get('lang', 'en-us'))
if not self.finished_training_event.is_set():
logger.debug('Waiting for training to finish...')
LOG.debug('Waiting for training to finish...')
self.finished_training_event.wait()
data = self.container.calc_intent(utt)

View File

@ -26,11 +26,10 @@ from adapt.intent import IntentBuilder
from mycroft.skills import time_rules
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'jdorleans'
logger = getLogger(__name__)
class ScheduledSkill(MycroftSkill):
@ -152,7 +151,7 @@ class ScheduledCRUDSkill(ScheduledSkill):
self.data = {}
self.repeat_data = {}
if basedir:
logger.debug('basedir argument is no longer required and is ' +
LOG.debug('basedir argument is no longer required and is ' +
'depreciated.')
self.basedir = basedir

View File

@ -32,10 +32,9 @@ import json
import sys
from threading import Timer
from os.path import isfile, join, exists, expanduser
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.api import DeviceApi
logger = getLogger(__name__)
SKILLS_DIR = "/opt/mycroft/skills"
@ -107,7 +106,7 @@ class SkillSettings(dict):
if self._skill_exist_in_backend() is False:
response = self._put_metadata(self.settings_meta)
except Exception as e:
logger.error(e)
LOG.error(e)
def _poll_skill_settings(self):
"""
@ -131,7 +130,7 @@ class SkillSettings(dict):
self.store()
except Exception as e:
logger.error(e)
LOG.error(e)
# poll backend every 60 seconds for new settings
Timer(60, self._poll_skill_settings).start()
@ -143,7 +142,7 @@ class SkillSettings(dict):
try:
return self.settings_meta["identifier"]
except Exception as e:
logger.error(e)
LOG.error(e)
return None
def load_skill_settings(self):
@ -159,7 +158,7 @@ class SkillSettings(dict):
except Exception as e:
# TODO: Show error on webUI. Dev will have to fix
# metadata to be able to edit later.
logger.error(e)
LOG.error(e)
def _get_settings(self):
"""

View File

@ -20,7 +20,7 @@ from speech_recognition import Recognizer
from mycroft.api import STTApi
from mycroft.configuration import ConfigurationManager
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
import re
@ -28,7 +28,6 @@ from requests import post
__author__ = "jdorleans"
LOG = getLogger("STT")
class STT(object):
@ -86,7 +85,7 @@ class WITSTT(TokenSTT):
super(WITSTT, self).__init__()
def execute(self, audio, language=None):
LOG.warn("WITSTT language should be configured at wit.ai settings.")
LOG.warning("WITSTT language should be configured at wit.ai settings.")
return self.recognizer.recognize_wit(audio, self.token)

View File

@ -27,13 +27,12 @@ import hashlib
from mycroft.client.enclosure.api import EnclosureAPI
from mycroft.configuration import ConfigurationManager
from mycroft.messagebus.message import Message
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.util import play_wav, play_mp3, check_for_signal, create_signal
import mycroft.util
__author__ = 'jdorleans'
LOGGER = getLogger(__name__)
class PlaybackThread(Thread):
@ -95,7 +94,7 @@ class PlaybackThread(Thread):
except Empty:
pass
except Exception, e:
LOGGER.exception(e)
LOG.exception(e)
if self._processing_queue:
self.tts.end_audio()
self._processing_queue = False
@ -204,7 +203,7 @@ class TTS(object):
key + '.' + self.type)
if os.path.exists(wav_file):
LOGGER.debug("TTS cache hit")
LOG.debug("TTS cache hit")
phonemes = self.load_phonemes(key)
else:
wav_file, phonemes = self.get_tts(sentence, wav_file)
@ -250,7 +249,7 @@ class TTS(object):
with open(pho_file, "w") as cachefile:
cachefile.write(phonemes)
except:
LOGGER.debug("Failed to write .PHO to cache")
LOG.debug("Failed to write .PHO to cache")
pass
def load_phonemes(self, key):
@ -268,7 +267,7 @@ class TTS(object):
phonemes = cachefile.read().strip()
return phonemes
except:
LOGGER.debug("Failed to read .PHO from cache")
LOG.debug("Failed to read .PHO from cache")
return None
def __del__(self):

View File

@ -25,8 +25,7 @@ from mycroft import MYCROFT_ROOT_PATH
from mycroft.configuration import ConfigurationManager
from mycroft.tts import TTS, TTSValidator
import mycroft.util
from mycroft.util.log import getLogger
LOGGER = getLogger(__name__)
from mycroft.util.log import LOG
__author__ = 'jdorleans', 'spenrod'
@ -83,7 +82,7 @@ class MimicValidator(TTSValidator):
try:
subprocess.call([BIN, '--version'])
except:
LOGGER.info("Failed to find mimic at: " + BIN)
LOG.info("Failed to find mimic at: " + BIN)
raise Exception(
'Mimic was not found. Run install-mimic.sh to install it.')

View File

@ -23,12 +23,11 @@ from requests_futures.sessions import FuturesSession
from mycroft.tts import TTS
from mycroft.util import remove_last_slash, play_wav
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.messagebus.message import Message
__author__ = 'jdorleans'
LOGGER = getLogger(__name__)
class RemoteTTS(TTS):
@ -54,7 +53,7 @@ class RemoteTTS(TTS):
self.begin_audio()
self.__play(req)
except Exception, e:
LOGGER.error(e.message)
LOG.error(e.message)
finally:
self.end_audio()
@ -86,7 +85,7 @@ class RemoteTTS(TTS):
self.__save(resp.content)
play_wav(self.filename).communicate()
else:
LOGGER.error(
LOG.error(
'%s Http Error: %s for url: %s' %
(resp.status_code, resp.reason, resp.url))

View File

@ -18,7 +18,7 @@
# Officially exported methods from this file:
# play_wav, play_mp3, get_cache_directory,
# resolve_resource_file, wait_while_speaking
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
from mycroft.util.parse import extract_datetime, extractnumber, normalize
from mycroft.util.format import nice_number, convert_number
@ -38,7 +38,6 @@ import mycroft.audio
__author__ = 'jdorleans'
logger = getLogger(__name__)
def resolve_resource_file(res_name):
@ -243,7 +242,7 @@ def is_speaking():
Returns:
bool: True while still speaking
"""
logger.info("mycroft.utils.is_speaking() is depreciated, use "
LOG.info("mycroft.utils.is_speaking() is depreciated, use "
"mycroft.audio.is_speaking() instead.")
return mycroft.audio.is_speaking()
@ -255,7 +254,7 @@ def wait_while_speaking():
briefly to ensure that any preceeding request to speak has time to
begin.
"""
logger.info("mycroft.utils.wait_while_speaking() is depreciated, use "
LOG.info("mycroft.utils.wait_while_speaking() is depreciated, use "
"mycroft.audio.wait_while_speaking() instead.")
return mycroft.audio.wait_while_speaking()
@ -263,6 +262,6 @@ def wait_while_speaking():
def stop_speaking():
# TODO: Less hacky approach to this once Audio Manager is implemented
# Skills should only be able to stop speech they've initiated
logger.info("mycroft.utils.stop_speaking() is depreciated, use "
LOG.info("mycroft.utils.stop_speaking() is depreciated, use "
"mycroft.audio.stop_speaking() instead.")
mycroft.audio.stop_speaking()

View File

@ -14,33 +14,113 @@
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
import json
import inspect
import logging
import sys
from traceback import format_exception
from os.path import isfile
from mycroft.util.json_helper import load_commented_json
SYSTEM_CONFIG = '/etc/mycroft/mycroft.conf'
__author__ = 'seanfitz'
log_level = "DEBUG"
if isfile(SYSTEM_CONFIG):
config = load_commented_json(SYSTEM_CONFIG)
log_level = config.get("log_level", "DEBUG")
FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, level=logging.getLevelName(log_level))
logger = logging.getLogger("MYCROFT")
def getLogger(name="MYCROFT"):
"""
Get a python logger
:param name: Module name for the logger
:return: an instance of logging.Logger
"""
"""Depreciated. Use LOG instead"""
return logging.getLogger(name)
class LOG:
"""
Custom logger class that acts like logging.Logger
The logger name is automatically generated by the module of the caller
Usage:
LOG.debug('My message: %s', debug_str)
LOG('custom_name').debug('Another message')
"""
_custom_name = None
@classmethod
def init(cls):
sys_config = '/etc/mycroft/mycroft.conf'
cls.level = logging.getLevelName(load_commented_json(sys_config)['log_level']
if isfile(sys_config) else 'DEBUG')
fmt = '%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - %(message)s'
datefmt = '%H:%M:%S'
formatter = logging.Formatter(fmt, datefmt)
cls.ch = logging.StreamHandler(sys.stdout)
cls.ch.setFormatter(formatter)
cls.create_logger('') # Enables logging in external modules
@classmethod
def create_logger(cls, name):
l = logging.getLogger(name)
l.propagate = False
if not hasattr(cls, 'level'):
cls.init()
l.addHandler(cls.ch)
l.setLevel(cls.level)
return l
def __init__(self, name):
LOG._custom_name = name
@classmethod
def _log(cls, func, args, kwargs):
if cls._custom_name is not None:
name = cls._custom_name
cls._custom_name = None
else:
# Stack:
# [0] - _log()
# [1] - debug(), info(), warning(), or error()
# [2] - caller
stack = inspect.stack()
# Record:
# [0] - frame object
# [1] - filename
# [2] - line number
# [3] - function
# ...
record = stack[2]
name = inspect.getmodule(record[0]).__name__ + ':' + record[3] + ':' + str(record[2])
func(cls.create_logger(name), *args, **kwargs)
@classmethod
def debug(cls, *args, **kwargs):
cls._log(logging.Logger.debug, args, kwargs)
@classmethod
def info(cls, *args, **kwargs):
cls._log(logging.Logger.info, args, kwargs)
@classmethod
def warning(cls, *args, **kwargs):
cls._log(logging.Logger.warning, args, kwargs)
@classmethod
def error(cls, *args, **kwargs):
cls._log(logging.Logger.error, args, kwargs)
@classmethod
def exception(cls, *args, **kwargs):
cls._log(logging.Logger.exception, args, kwargs)
@classmethod
def print_trace(cls, location='', warn=False, *args):
trace_lines = format_exception(*sys.exc_info())
if warn:
intro = 'Warning' + ('in ' + location + ': ' if location else ': ')
trace_str = intro + trace_lines[-1].strip()
t = logging.Logger.info
else:
trace_str = '\n' + ''.join(trace_lines)
if location:
trace_str = '\n=== ' + location + ' ===' + trace_str
trace_str = '\n' + trace_str
t = logging.Logger.error
cls._log(t, trace_str, args)

View File

@ -20,13 +20,12 @@ import os
import subprocess
from setuptools import find_packages
import shutil
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'seanfitz'
BASEDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
logger = getLogger(__name__)
def place_manifest(manifest_file):
@ -44,8 +43,8 @@ def get_version():
["git", "rev-parse", "--short", "HEAD"]).strip()
except subprocess.CalledProcessError, e2:
version = "development"
logger.debug(e)
logger.exception(e2)
LOG.debug(e)
LOG.exception(e2)
return version

View File

@ -3,9 +3,8 @@ import os.path
import tempfile
import mycroft
import time
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
LOG = getLogger(__name__)
def get_ipc_directory(domain=None):
@ -48,7 +47,7 @@ def ensure_directory_exists(dir, domain=None):
save = os.umask(0)
os.makedirs(dir, 0777) # give everyone rights to r/w here
except OSError:
LOG.warn("Failed to create: " + dir)
LOG.warning("Failed to create: " + dir)
pass
finally:
os.umask(save)

View File

@ -18,7 +18,7 @@
import json
from genericpath import exists, isfile
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'augustnmonteiro'
@ -32,7 +32,6 @@ CORE_VERSION_BUILD = 20
CORE_VERSION_STR = (str(CORE_VERSION_MAJOR) + "." +
str(CORE_VERSION_MINOR) + "." +
str(CORE_VERSION_BUILD))
LOG = getLogger(__name__)
class VersionManager(object):

View File

@ -14,10 +14,9 @@ from mycroft.configuration import ConfigurationManager
from mycroft.messagebus.message import Message
from adapt.intent import IntentBuilder
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'eward'
logger = getLogger(__name__)
class MockEmitter(object):

View File

@ -2,11 +2,10 @@ from datetime import datetime, timedelta
import unittest
from mycroft.skills.scheduled_skills import ScheduledSkill
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
__author__ = 'eward'
logger = getLogger(__name__)
class ScheduledSkillTest(unittest.TestCase):