Logger improvements

This commit is contained in:
Yegor Vialov 2018-10-27 01:24:23 +03:00
parent 8fb0d61a84
commit 5e834b0645
8 changed files with 63 additions and 50 deletions

View File

@ -19,7 +19,7 @@ class EntityCollection {
_allEntities.clear(); _allEntities.clear();
//views.clear(); //views.clear();
TheLogger.log("Debug","Parsing ${rawData.length} Home Assistant entities"); TheLogger.debug("Parsing ${rawData.length} Home Assistant entities");
rawData.forEach((rawEntityData) { rawData.forEach((rawEntityData) {
addFromRaw(rawEntityData); addFromRaw(rawEntityData);
}); });

View File

@ -55,16 +55,16 @@ class HomeAssistant {
_password = password; _password = password;
_authType = authType; _authType = authType;
_useLovelace = useLovelace; _useLovelace = useLovelace;
TheLogger.log("Debug", "Use lovelace is $_useLovelace"); TheLogger.debug( "Use lovelace is $_useLovelace");
} }
Future fetch() { Future fetch() {
if ((_fetchCompleter != null) && (!_fetchCompleter.isCompleted)) { if ((_fetchCompleter != null) && (!_fetchCompleter.isCompleted)) {
TheLogger.log("Warning","Previous fetch is not complited"); TheLogger.warning("Previous fetch is not complited");
} else { } else {
_fetchCompleter = new Completer(); _fetchCompleter = new Completer();
_fetchTimer = Timer(fetchTimeout, () { _fetchTimer = Timer(fetchTimeout, () {
TheLogger.log("Error", "Data fetching timeout"); TheLogger.error( "Data fetching timeout");
disconnect().then((_) { disconnect().then((_) {
_completeFetching({ _completeFetching({
"errorCode": 9, "errorCode": 9,
@ -84,7 +84,7 @@ class HomeAssistant {
disconnect() async { disconnect() async {
if ((_hassioChannel != null) && (_hassioChannel.closeCode == null) && (_hassioChannel.sink != null)) { if ((_hassioChannel != null) && (_hassioChannel.closeCode == null) && (_hassioChannel.sink != null)) {
await _hassioChannel.sink.close().timeout(Duration(seconds: 3), await _hassioChannel.sink.close().timeout(Duration(seconds: 3),
onTimeout: () => TheLogger.log("Debug", "Socket sink closed") onTimeout: () => TheLogger.debug( "Socket sink closed")
); );
await _socketSubscription.cancel(); await _socketSubscription.cancel();
_hassioChannel = null; _hassioChannel = null;
@ -94,15 +94,15 @@ class HomeAssistant {
Future _connection() { Future _connection() {
if ((_connectionCompleter != null) && (!_connectionCompleter.isCompleted)) { if ((_connectionCompleter != null) && (!_connectionCompleter.isCompleted)) {
TheLogger.log("Debug","Previous connection is not complited"); TheLogger.debug("Previous connection is not complited");
} else { } else {
if ((_hassioChannel == null) || (_hassioChannel.closeCode != null)) { if ((_hassioChannel == null) || (_hassioChannel.closeCode != null)) {
_connectionCompleter = new Completer(); _connectionCompleter = new Completer();
autoReconnect = false; autoReconnect = false;
disconnect().then((_){ disconnect().then((_){
TheLogger.log("Debug", "Socket connecting..."); TheLogger.debug( "Socket connecting...");
_connectionTimer = Timer(connectTimeout, () { _connectionTimer = Timer(connectTimeout, () {
TheLogger.log("Error", "Socket connection timeout"); TheLogger.error( "Socket connection timeout");
_handleSocketError(null); _handleSocketError(null);
}); });
if (_socketSubscription != null) { if (_socketSubscription != null) {
@ -125,15 +125,15 @@ class HomeAssistant {
} }
void _handleSocketClose() { void _handleSocketClose() {
TheLogger.log("Debug","Socket disconnected. Automatic reconnect is $autoReconnect"); TheLogger.debug("Socket disconnected. Automatic reconnect is $autoReconnect");
if (autoReconnect) { if (autoReconnect) {
_reconnect(); _reconnect();
} }
} }
void _handleSocketError(e) { void _handleSocketError(e) {
TheLogger.log("Error","Socket stream Error: $e"); TheLogger.error("Socket stream Error: $e");
TheLogger.log("Debug","Automatic reconnect is $autoReconnect"); TheLogger.debug("Automatic reconnect is $autoReconnect");
if (autoReconnect) { if (autoReconnect) {
_reconnect(); _reconnect();
} else { } else {
@ -180,7 +180,7 @@ class HomeAssistant {
_fetchCompleter.completeError(error); _fetchCompleter.completeError(error);
} else { } else {
autoReconnect = true; autoReconnect = true;
TheLogger.log("Debug", "Fetch complete successful"); TheLogger.debug( "Fetch complete successful");
_fetchCompleter.complete(); _fetchCompleter.complete();
} }
} }
@ -220,19 +220,19 @@ class HomeAssistant {
} else if (data["id"] == _userInfoMessageId) { } else if (data["id"] == _userInfoMessageId) {
_parseUserInfo(data); _parseUserInfo(data);
} else if (data["id"] == _currentMessageId) { } else if (data["id"] == _currentMessageId) {
TheLogger.log("Debug","[Received] => Request id:$_currentMessageId was successful"); TheLogger.debug("[Received] => Request id:$_currentMessageId was successful");
} }
} else if (data["type"] == "event") { } else if (data["type"] == "event") {
if ((data["event"] != null) && (data["event"]["event_type"] == "state_changed")) { if ((data["event"] != null) && (data["event"]["event_type"] == "state_changed")) {
TheLogger.log("Debug","[Received] => ${data['type']}.${data["event"]["event_type"]}: ${data["event"]["data"]["entity_id"]}"); TheLogger.debug("[Received] => ${data['type']}.${data["event"]["event_type"]}: ${data["event"]["data"]["entity_id"]}");
_handleEntityStateChange(data["event"]["data"]); _handleEntityStateChange(data["event"]["data"]);
} else if (data["event"] != null) { } else if (data["event"] != null) {
TheLogger.log("Warning","Unhandled event type: ${data["event"]["event_type"]}"); TheLogger.warning("Unhandled event type: ${data["event"]["event_type"]}");
} else { } else {
TheLogger.log("Error","Event is null: $message"); TheLogger.error("Event is null: $message");
} }
} else { } else {
TheLogger.log("Warning","Unknown message type: $message"); TheLogger.warning("Unknown message type: $message");
} }
} }
@ -292,7 +292,7 @@ class HomeAssistant {
} }
void _sendAuthMessageRaw(String message) { void _sendAuthMessageRaw(String message) {
TheLogger.log("Debug", "[Sending] ==> auth request"); TheLogger.debug( "[Sending] ==> auth request");
_hassioChannel.sink.add(message); _hassioChannel.sink.add(message);
} }
@ -301,11 +301,11 @@ class HomeAssistant {
if (queued) _messageQueue.add(message); if (queued) _messageQueue.add(message);
_connection().then((r) { _connection().then((r) {
_messageQueue.getActualMessages().forEach((message){ _messageQueue.getActualMessages().forEach((message){
TheLogger.log("Debug", "[Sending queued] ==> $message"); TheLogger.debug( "[Sending queued] ==> $message");
_hassioChannel.sink.add(message); _hassioChannel.sink.add(message);
}); });
if (!queued) { if (!queued) {
TheLogger.log("Debug", "[Sending] ==> $message"); TheLogger.debug( "[Sending] ==> $message");
_hassioChannel.sink.add(message); _hassioChannel.sink.add(message);
} }
sendCompleter.complete(); sendCompleter.complete();
@ -332,7 +332,7 @@ class HomeAssistant {
} }
void _handleEntityStateChange(Map eventData) { void _handleEntityStateChange(Map eventData) {
//TheLogger.log("Debug", "New state for ${eventData['entity_id']}"); //TheLogger.debug( "New state for ${eventData['entity_id']}");
Map data = Map.from(eventData); Map data = Map.from(eventData);
entities.updateState(data); entities.updateState(data);
eventBus.fire(new StateChangedEvent(data["entity_id"], null, false)); eventBus.fire(new StateChangedEvent(data["entity_id"], null, false));
@ -371,12 +371,12 @@ class HomeAssistant {
void _parseLovelace() { void _parseLovelace() {
ui = HomeAssistantUI(); ui = HomeAssistantUI();
TheLogger.log("debug","Parsing lovelace config"); TheLogger.debug("Parsing lovelace config");
TheLogger.log("debug","--Title: ${_rawLovelaceData["title"]}"); TheLogger.debug("--Title: ${_rawLovelaceData["title"]}");
int viewCounter = 0; int viewCounter = 0;
TheLogger.log("debug","--Views count: ${_rawLovelaceData['views'].length}"); TheLogger.debug("--Views count: ${_rawLovelaceData['views'].length}");
_rawLovelaceData["views"].forEach((rawView){ _rawLovelaceData["views"].forEach((rawView){
TheLogger.log("debug","----view id: ${rawView['id']}"); TheLogger.debug("----view id: ${rawView['id']}");
HAView view = HAView( HAView view = HAView(
count: viewCounter, count: viewCounter,
id: rawView['id'], id: rawView['id'],
@ -395,10 +395,10 @@ class HomeAssistant {
List<HACard> result = []; List<HACard> result = [];
rawCards.forEach((rawCard){ rawCards.forEach((rawCard){
if (rawCard["cards"] != null) { if (rawCard["cards"] != null) {
TheLogger.log("debug","------card: ${rawCard['type']} has child cards"); TheLogger.debug("------card: ${rawCard['type']} has child cards");
result.addAll(_createLovelaceCards(rawCard["cards"])); result.addAll(_createLovelaceCards(rawCard["cards"]));
} else { } else {
TheLogger.log("debug","------card: ${rawCard['type']}"); TheLogger.debug("------card: ${rawCard['type']}");
HACard card = HACard( HACard card = HACard(
id: "card", id: "card",
name: rawCard["title"] name: rawCard["title"]
@ -436,7 +436,7 @@ class HomeAssistant {
ui = HomeAssistantUI(); ui = HomeAssistantUI();
int viewCounter = 0; int viewCounter = 0;
if (!entities.hasDefaultView) { if (!entities.hasDefaultView) {
TheLogger.log("Debug", "--Default view"); TheLogger.debug( "--Default view");
HAView view = HAView( HAView view = HAView(
count: viewCounter, count: viewCounter,
id: "group.default_view", id: "group.default_view",
@ -449,7 +449,7 @@ class HomeAssistant {
viewCounter += 1; viewCounter += 1;
} }
entities.viewEntities.forEach((viewEntity) { entities.viewEntities.forEach((viewEntity) {
TheLogger.log("Debug", "--View: ${viewEntity.entityId}"); TheLogger.debug( "--View: ${viewEntity.entityId}");
HAView view = HAView( HAView view = HAView(
count: viewCounter, count: viewCounter,
id: viewEntity.entityId, id: viewEntity.entityId,
@ -473,9 +473,9 @@ class HomeAssistant {
DateTime now = DateTime.now(); DateTime now = DateTime.now();
//String endTime = formatDate(now, [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, z]); //String endTime = formatDate(now, [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, z]);
String startTime = formatDate(now.subtract(Duration(hours: 24)), [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, z]); String startTime = formatDate(now.subtract(Duration(hours: 24)), [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, z]);
TheLogger.log("Debug", "$startTime"); TheLogger.debug( "$startTime");
String url = "$homeAssistantWebHost/api/history/period/$startTime?&filter_entity_id=$entityId&skip_initial_state"; String url = "$homeAssistantWebHost/api/history/period/$startTime?&filter_entity_id=$entityId&skip_initial_state";
TheLogger.log("Debug", "$url"); TheLogger.debug( "$url");
http.Response historyResponse; http.Response historyResponse;
if (_authType == "access_token") { if (_authType == "access_token") {
historyResponse = await http.get(url, headers: { historyResponse = await http.get(url, headers: {
@ -492,7 +492,7 @@ class HomeAssistant {
if (_history is Map) { if (_history is Map) {
return null; return null;
} else if (_history is List) { } else if (_history is List) {
TheLogger.log("Debug", "${_history[0].toString()}"); TheLogger.debug( "${_history[0].toString()}");
return _history; return _history;
} }
} }

View File

@ -51,7 +51,6 @@ class _LogViewPageState extends State<LogViewPage> {
), ),
body: TextField( body: TextField(
maxLines: null, maxLines: null,
controller: TextEditingController( controller: TextEditingController(
text: _logData text: _logData
), ),

View File

@ -34,7 +34,7 @@ String homeAssistantWebHost;
void main() { void main() {
FlutterError.onError = (errorDetails) { FlutterError.onError = (errorDetails) {
TheLogger.log("Error", "${errorDetails.exception}"); TheLogger.error( "${errorDetails.exception}");
if (TheLogger.isInDebugMode) { if (TheLogger.isInDebugMode) {
FlutterError.dumpErrorToConsole(errorDetails); FlutterError.dumpErrorToConsole(errorDetails);
} }
@ -43,7 +43,8 @@ void main() {
runZoned(() { runZoned(() {
runApp(new HAClientApp()); runApp(new HAClientApp());
}, onError: (error, stack) { }, onError: (error, stack) {
TheLogger.log("Global error", "$error"); TheLogger.error("$error");
TheLogger.error("$stack");
if (TheLogger.isInDebugMode) { if (TheLogger.isInDebugMode) {
debugPrint("$stack"); debugPrint("$stack");
} }
@ -107,7 +108,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
_homeAssistant = HomeAssistant(); _homeAssistant = HomeAssistant();
_settingsSubscription = eventBus.on<SettingsChangedEvent>().listen((event) { _settingsSubscription = eventBus.on<SettingsChangedEvent>().listen((event) {
TheLogger.log("Debug","Settings change event: reconnect=${event.reconnect}"); TheLogger.debug("Settings change event: reconnect=${event.reconnect}");
if (event.reconnect) { if (event.reconnect) {
_homeAssistant.disconnect().then((_){ _homeAssistant.disconnect().then((_){
_initialLoad(); _initialLoad();
@ -131,7 +132,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
@override @override
void didChangeAppLifecycleState(AppLifecycleState state) { void didChangeAppLifecycleState(AppLifecycleState state) {
TheLogger.log("Debug","$state"); TheLogger.debug("$state");
if (state == AppLifecycleState.resumed && _settingsLoaded) { if (state == AppLifecycleState.resumed && _settingsLoaded) {
_refreshData(); _refreshData();
} }
@ -207,7 +208,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
//_instanceConfig = _homeAssistant.instanceConfig; //_instanceConfig = _homeAssistant.instanceConfig;
_entities = _homeAssistant.entities; _entities = _homeAssistant.entities;
//_uiViewsCount = _homeAssistant.viewsCount; //_uiViewsCount = _homeAssistant.viewsCount;
//TheLogger.log("Debug","_uiViewsCount=$_uiViewsCount"); //TheLogger.debug("_uiViewsCount=$_uiViewsCount");
_isLoading = 0; _isLoading = 0;
}); });
}).catchError((e) { }).catchError((e) {

View File

@ -49,7 +49,7 @@ class HAView {
childEntities.forEach((entity) { childEntities.forEach((entity) {
if (entity.isBadge) { if (entity.isBadge) {
badges.add(entity); badges.add(entity);
TheLogger.log("Debug","----Badge: ${entity.entityId}"); TheLogger.debug("----Badge: ${entity.entityId}");
} else { } else {
if (!entity.isGroup) { if (!entity.isGroup) {
String groupIdToAdd = "${entity.domain}.${entity.domain}$count"; String groupIdToAdd = "${entity.domain}.${entity.domain}$count";
@ -58,14 +58,14 @@ class HAView {
id: groupIdToAdd, id: groupIdToAdd,
name: entity.domain name: entity.domain
); );
TheLogger.log("Debug","----Creating card: $groupIdToAdd"); TheLogger.debug("----Creating card: $groupIdToAdd");
card.entities.add(entity); card.entities.add(entity);
autoGeneratedCards.add(card); autoGeneratedCards.add(card);
} else { } else {
autoGeneratedCards.firstWhere((card) => card.id == groupIdToAdd).entities.add(entity); autoGeneratedCards.firstWhere((card) => card.id == groupIdToAdd).entities.add(entity);
} }
} else { } else {
TheLogger.log("Debug","----Card: ${entity.entityId}"); TheLogger.debug("----Card: ${entity.entityId}");
HACard card = HACard( HACard card = HACard(
name: entity.displayName, name: entity.displayName,
id: entity.entityId, id: entity.entityId,
@ -163,7 +163,7 @@ class NewViewWidgetState extends State<NewViewWidget> {
Future _refreshData() { Future _refreshData() {
if ((_refreshCompleter != null) && (!_refreshCompleter.isCompleted)) { if ((_refreshCompleter != null) && (!_refreshCompleter.isCompleted)) {
TheLogger.log("Debug","Previous data refresh is still in progress"); TheLogger.debug("Previous data refresh is still in progress");
} else { } else {
_refreshCompleter = Completer(); _refreshCompleter = Completer();
eventBus.fire(RefreshDataEvent()); eventBus.fire(RefreshDataEvent());

View File

@ -20,12 +20,25 @@ class TheLogger {
return inDebugMode; return inDebugMode;
} }
static void log(String level, String message) { static void error(String message) {
_writeToLog("Error", message);
}
static void warning(String message) {
_writeToLog("Warning", message);
}
static void debug(String message) {
_writeToLog("Debug", message);
}
static void _writeToLog(String level, String message) {
if (isInDebugMode) { if (isInDebugMode) {
debugPrint('$message'); debugPrint('$message');
} }
_log.add("[$level] : $message"); DateTime t = DateTime.now();
if (_log.length > 50) { _log.add("${formatDate(t, ["mm","dd"," ","HH",":","nn",":","ss"])} [$level] : $message");
if (_log.length > 100) {
_log.removeAt(0); _log.removeAt(0);
} }
} }
@ -37,7 +50,7 @@ class HAUtils {
if (await canLaunch(url)) { if (await canLaunch(url)) {
await launch(url); await launch(url);
} else { } else {
TheLogger.log("Error", "Could not launch $url"); TheLogger.error( "Could not launch $url");
} }
} }
} }

View File

@ -142,7 +142,7 @@ class _TextInputStateWidgetState extends State<TextInputStateWidget> {
}), }),
); );
} else { } else {
TheLogger.log("Warning", "Unsupported input mode for ${entity.entityId}"); TheLogger.warning( "Unsupported input mode for ${entity.entityId}");
return SimpleEntityState(); return SimpleEntityState();
} }
} }
@ -694,7 +694,7 @@ class _CoverControlWidgetState extends State<CoverControlWidget> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final entityModel = EntityModel.of(context); final entityModel = EntityModel.of(context);
final CoverEntity entity = entityModel.entity; final CoverEntity entity = entityModel.entity;
TheLogger.log("debug", "${entity.state}"); TheLogger.debug("${entity.state}");
if (_changedHere) { if (_changedHere) {
_changedHere = false; _changedHere = false;
} else { } else {
@ -841,7 +841,7 @@ class _LightControlsWidgetState extends State<LightControlsWidget> {
setState(() { setState(() {
_tmpColor = color; _tmpColor = color;
_changedHere = true; _changedHere = true;
TheLogger.log("Debug", "Color: [${color.red}, ${color.green}, ${color.blue}]"); TheLogger.debug( "Color: [${color.red}, ${color.green}, ${color.blue}]");
if ((color == Colors.black) || ((color.red == color.green) && (color.green == color.blue))) { if ((color == Colors.black) || ((color.red == color.green) && (color.green == color.blue))) {
eventBus.fire(new ServiceCallEvent( eventBus.fire(new ServiceCallEvent(
entity.domain, "turn_off", entity.entityId, entity.domain, "turn_off", entity.entityId,

View File

@ -502,7 +502,7 @@ class DateTimeStateWidget extends StatelessWidget {
} }
}); });
} else { } else {
TheLogger.log("Warning", "${entity.entityId} has no date and no time"); TheLogger.warning( "${entity.entityId} has no date and no time");
} }
} }