Skip to content

Commit

Permalink
add logging
Browse files Browse the repository at this point in the history
  • Loading branch information
moweiran committed Jan 3, 2024
1 parent f24f9af commit fd4f07b
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 27 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@
pubspec.lock

/assets
/lib/json2model_gen
/lib/json2model_gen
json2model.yaml
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
## 1.1.0

- add logging

## 1.0.9

- json_parse_model readme link

## 1.0.7

- add more information for install
Expand Down
18 changes: 12 additions & 6 deletions lib/src/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import 'dart:async';
import 'package:build/build.dart';
import 'package:code_builder/code_builder.dart';
import 'package:dart_style/dart_style.dart';
import 'package:logging/logging.dart';

import 'http_parse.dart';
import 'json_parse_model_base.dart';
import 'source_parse.dart';

Logger logger = Logger('builder=>build');

class Json2ModelPrintBuilder implements Builder {
final BuilderOptions options;
Json2ModelPrintBuilder({
Expand All @@ -17,7 +20,7 @@ class Json2ModelPrintBuilder implements Builder {
@override
FutureOr<void> build(BuildStep buildStep) async {
try {
print('options=${options.config}');
logger.info('options=${options.config}');
final inputId = buildStep.inputId;
var contents = await buildStep.readAsString(inputId);
final sourceConfig = SourceParse.instance.parse(contents);
Expand All @@ -31,11 +34,15 @@ class Json2ModelPrintBuilder implements Builder {
host: options.config['host'],
token: options.config['token'],
);
if (jsonMap == null) {
logger.info('$tag jsonMap is null');
return;
}

if (jsonMap.isNotEmpty) {
final data = jsonMap['data'];
if (data is bool || data is String || data is int) {
print('$tag is bool or string or int');
logger.info('$tag is bool or string or int');
} else if (data is List) {
if (data.first is Map<String, dynamic>) {
_buildClassCode(
Expand All @@ -44,7 +51,7 @@ class Json2ModelPrintBuilder implements Builder {
resultCodes: resultCodes,
);
} else {
print('$tag is Map<bool> or Map<String> or Map<bool>');
logger.info('$tag is Map<bool> or Map<String> or Map<bool>');
}
} else if (data is Map<String, dynamic>) {
_buildClassCode(
Expand All @@ -56,12 +63,11 @@ class Json2ModelPrintBuilder implements Builder {
await buildStep.writeAsString(outputId,
'/// Generated by build_runner, don\'t modify it.\n${resultCodes.join("\n")}');
} else {
print(
logger.info(
'please check your assets/json/xxx.json file exist or formatter!');
}
} catch (e, s) {
print(e);
print(s);
logger.info('error', e, s);
}
}

Expand Down
43 changes: 26 additions & 17 deletions lib/src/http_parse.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,43 @@ import 'dart:io';
import 'package:http/http.dart' as http;

import 'build_config.dart';
import 'builder.dart';
import 'load_config.dart';

class HttpParse {
HttpParse._();
static final instance = HttpParse._();
JsonBuildConfig? buildConfig;
Future<Map<String, dynamic>> get(
Future<Map<String, dynamic>?> get(
String api, {
String? host,
String? token,
}) async {
if (host != null && host.isNotEmpty && token != null && token.isNotEmpty) {
print('read buid config from options');
buildConfig = JsonBuildConfig(host: host, token: token);
} else {
print('read buid config from yaml file');
buildConfig ??= await loadConfigs();
}
try {
if (host != null &&
host.isNotEmpty &&
token != null &&
token.isNotEmpty) {
logger.info('read buid config from options');
buildConfig = JsonBuildConfig(host: host, token: token);
} else {
logger.info('read buid config from yaml file');
buildConfig ??= await loadConfigs();
}

if (buildConfig!.host.isEmpty || buildConfig!.token.isEmpty) {
return {};
if (buildConfig!.host.isEmpty || buildConfig!.token.isEmpty) {
return {};
}
final String url = '${buildConfig!.host}/$api';
var uri = Uri.parse(url);
var response = await http.get(uri, headers: {
HttpHeaders.authorizationHeader: 'Bearer ${buildConfig!.token}',
});
logger.info('$url =>\n ${response.body}');
return json.decode(response.body);
} catch (e, s) {
logger.warning('httpParse', e, s);
return null;
}
final String url = '${buildConfig!.host}/$api';
var uri = Uri.parse(url);
var response = await http.get(uri, headers: {
HttpHeaders.authorizationHeader: 'Bearer ${buildConfig!.token}',
});
print(response.body);
return json.decode(response.body);
}
}
6 changes: 4 additions & 2 deletions lib/src/load_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@ import 'dart:io';
import 'package:yaml/yaml.dart';

import 'build_config.dart';
import 'builder.dart';

Future<JsonBuildConfig> loadConfigs() async {
print('start load config');
logger.info('start load config');
final File file = File.fromUri(Uri.file("json2model.yaml"));
if (await file.exists()) {
final config = await file.readAsString();
final doc = loadYaml(config);
final jsonString = json.encode(doc);
return JsonBuildConfig.fromJson(json.decode(jsonString));
} else {
print("Environment variable file doesn't exist at `json2model.yaml`.");
logger
.info("Environment variable file doesn't exist at `json2model.yaml`.");
return JsonBuildConfig(host: '', token: '');
}
}
37 changes: 37 additions & 0 deletions lib/src/logging.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

import 'package:logging/logging.dart';

const Symbol logKey = #buildLog;

final _default = Logger('build.fallback');

/// The log instance for the currently running BuildStep.
///
/// Will be `null` when not running within a build.
Logger get log => Zone.current[logKey] as Logger? ?? _default;

/// Runs [fn] in an error handling [Zone].
///
/// Any calls to [print] will be logged with `log.warning`, and any errors will
/// be logged with `log.severe`.
///
/// Completes with the first error or result of `fn`, whichever comes first.
Future<T> scopeLogAsync<T>(Future<T> Function() fn, Logger log) {
var done = Completer<T>();
runZonedGuarded(fn, (e, st) {
log.severe('', e, st);
if (done.isCompleted) return;
done.completeError(e, st);
}, zoneSpecification: ZoneSpecification(print: (self, parent, zone, message) {
log.warning(message);
}), zoneValues: {logKey: log})?.then((result) {
if (done.isCompleted) return;
done.complete(result);
});
return done.future;
}
3 changes: 2 additions & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: json_parse_model
description: A package for convert from json to model by http api
version: 1.0.9
version: 1.1.0
repository: https://github.com/moweiran/json_parse_model.git

environment:
Expand All @@ -13,6 +13,7 @@ dependencies:
code_builder: ^4.9.0
dart_style: ^2.3.4
http: ^1.1.2
logging: ^1.2.0
yaml: ^3.1.2
# path: ^1.8.0

Expand Down

0 comments on commit fd4f07b

Please sign in to comment.