cfgstore 2.2.8

Sign up to get free protection for your applications and to get access to all the features.
Files changed (4) hide show
  1. checksums.yaml +7 -0
  2. data/lib/app-config.rb +62 -0
  3. data/lib/app-logger.rb +76 -0
  4. metadata +59 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c797f16240a8dc25a6ea0aea48c7c4a40125f1de221d121ef9cb00b4a485ed9c
4
+ data.tar.gz: fe0b79cc30fd18cb8db96eb7386e303362b47806e84f295bc9923205f4f5206b
5
+ SHA512:
6
+ metadata.gz: 6099f710167e47a398786bd343b3279a046e3b686a224c182735179844b815ac319a8d6434da6094cb5b6e93b5d3c45f5bc777b79cd96aa286a716c2fd5002da
7
+ data.tar.gz: fe98b93f2379c5f180455358bff9f00a0e095379335cb9e208379c9c9b8019c11264f21c611a0fbb09aaa3a6edb17d7e41d1617474b49656a4b1a9e2a8fcc35c
@@ -0,0 +1,62 @@
1
+ require 'yaml'
2
+ require 'singleton'
3
+ require 'pathname'
4
+ require 'monkey-hash'
5
+
6
+ module App
7
+
8
+ ##
9
+ # СДЕЛАТЬ: автоперезагрузку при изменении файла.
10
+
11
+ module Config
12
+
13
+ ##
14
+ # Создаёт корневой словарь настроек.
15
+ # Автоматически создаёт глобальную переменную Cfg.
16
+ # Автоматически подгружает AMQP и HTTP роуты.
17
+
18
+ module_function
19
+ def init( approot: nil, configdir: 'config', filename: 'cfg', env: ( ENV['APP_ENV'] || 'development' ) )
20
+ raise NoMethodError.new('Config already defined.') if defined?( ::Cfg )
21
+ root = Pathname( approot || Pathname( __FILE__ ).dirname ).expand_path.to_s
22
+ env = env.to_sym.freeze
23
+ config = {}
24
+ # Все настройки приложения + роуты
25
+ configfile = "#{ root }/#{ configdir }/#{ filename }.#{ env }.yml"
26
+ amqp_routesfile = "#{ root }/#{ configdir }/amqp.#{ env }.yml"
27
+ http_routesfile = "#{ root }/#{ configdir }/http.#{ env }.yml"
28
+
29
+ # raise ArgumentError.new("Не найден #{ configfile }!") unless File.exist?( configfile )
30
+ # raise ArgumentError.new("Не найден #{ amqp_routesfile }!") unless File.exist?( amqp_routesfile )
31
+ # Кто первый встал, того и тапки.
32
+ Kernel.const_set('Cfg', config)
33
+ config.merge!( YAML.load_file( configfile ).keys_to_symbols ) rescue nil
34
+ $0 += "[ #{ config.app.id } ]" if config.app? && config.app.id?
35
+ config[ :app ] ||= { id: $0 }
36
+ config.app[ :log ] ||= ENV['APP_LOG']
37
+
38
+ config.merge!({
39
+ root: root,
40
+ env: env,
41
+ configdir: "#{ root }/#{ configdir }",
42
+ amqproutes: File.exist?( amqp_routesfile ) ? YAML.load_file( amqp_routesfile ).keys_to_symbols : {},
43
+ httproutes: File.exist?( http_routesfile ) ? YAML.load_file( http_routesfile ).keys_to_symbols : {}
44
+ })
45
+
46
+ config[:loglevel] =
47
+ begin
48
+ Kernel.const_get("Logger::#{
49
+ ( ENV['LOG_LEVEL'] || config.app.loglevel || ( env == :production ? :WARN : :DEBUG ) ).to_s.upcase
50
+ }")
51
+ rescue
52
+ Logger::DEBUG
53
+ end
54
+ config
55
+ end
56
+
57
+ def remove
58
+ Kernel.send( :remove_const, 'Cfg' ) if defined?( Cfg )
59
+ end
60
+
61
+ end
62
+ end
@@ -0,0 +1,76 @@
1
+ require 'logger'
2
+ require 'monkey-hash'
3
+ ##
4
+ # Печататель протоколов с удобной настройкой вывода и фильтрацией спама от Bunny.
5
+ # Использует предварительно настроенный Cfg
6
+
7
+ module App
8
+ class Logger < ::Logger
9
+
10
+ attr_accessor :main_formatter, :amqp_formatter, :logdev
11
+
12
+ def base_formatter
13
+ return proc { |severity, datetime, progname, msg|
14
+ # "#{ severity[0] }°#{ datetime.strftime '%d/%m-%H:%M:%S' }°#{ Thread.current.object_id }°#{ Process.pid }°#{ "%20s" % caller_locations[0..4].last.label }:#{ "%03d" % caller_locations[0..4].last.lineno.to_i }—#{ msg }\n"
15
+ "#{ severity[0] } #{ datetime.strftime '%d/%m-%H:%M:%S' } #{ msg }\n"
16
+ }
17
+ end
18
+ def mq_formatter
19
+ # Убираем некоторую вредность из логгера Кролика
20
+ return proc { |severity, datetime, progname, msg|
21
+ if msg !~ /Using TLS but/ && severity != 'DEBUG'
22
+ msg.force_encoding('UTF-8')
23
+ if severity == 'ERROR'
24
+ msg += <<~BACKTACE
25
+
26
+ Thread #{ Thread.current.inspect }
27
+ Process #{ Process.pid }
28
+ #{ "===BACKTACE:===\n" + caller.join("\n") + "\n===" }
29
+ BACKTACE
30
+ end
31
+ base_formatter.call(severity, datetime, progname, '(ѣ)' + msg )
32
+ end
33
+ }
34
+ end
35
+
36
+ def initialize( dest = nil, formatter: nil, bunny_formatter: nil )
37
+ raise 'Log уже есть.' if defined?( ::Log )
38
+ raise 'Сначала нужны настройки.' unless defined?( ::Cfg )
39
+
40
+ @main_formatter = formatter || base_formatter
41
+ @amqp_formatter = bunny_formatter || mq_formatter || @main_formatter
42
+
43
+ raise 'formatter должны быть Proc' if ! @main_formatter.is_a?(Proc) || ! @amqp_formatter.is_a?(Proc)
44
+
45
+ @logdev =
46
+ case dest ||= Cfg.app.log
47
+ when 'stderr', 'syslog', nil
48
+ # $stdout.close
49
+ $stdout.reopen $stderr
50
+ when 'stdout'
51
+ # $stderr.close
52
+ $stderr.reopen $stdout
53
+ else
54
+ Cfg.app.log = "#{ Cfg.root }/#{ Cfg.app.log }" unless Cfg.app.log =~ %r{^/}
55
+ FileUtils.mkdir_p Pathname.new( Cfg.app.log ).dirname
56
+ logf = File.open( Cfg.app.log, 'a' )
57
+ logf.sync = true
58
+ $stderr.reopen logf
59
+ $stdout.reopen logf
60
+ logf
61
+ end
62
+ super @logdev, progname: Cfg.app.progname, level: Cfg.loglevel, formatter: @main_formatter
63
+ Kernel.const_set 'Log', self
64
+ Kernel.const_set 'MQLog', ::Logger.new( @logdev, progname: "#{ Cfg.app.progname }+Bunny", level: Cfg.loglevel, formatter: @amqp_formatter )
65
+ Log.info{"#{ Cfg.env } started. thread #{ Thread.current.object_id }."}
66
+ self
67
+ end
68
+
69
+ def remove
70
+ Kernel.send( :remove_const, 'Log' ) if defined?( Log )
71
+ Kernel.send( :remove_const, 'Log' ) if defined?( MQLog )
72
+ end
73
+
74
+ end
75
+
76
+ end
metadata ADDED
@@ -0,0 +1,59 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cfgstore
3
+ version: !ruby/object:Gem::Version
4
+ version: 2.2.8
5
+ platform: ruby
6
+ authors:
7
+ - deemytch
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2020-07-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: monkey-hash
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description: Loads from yaml, determines defaults and serves settings for the small
28
+ program.
29
+ email: aspamkiller@yandex.ru
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - lib/app-config.rb
35
+ - lib/app-logger.rb
36
+ homepage:
37
+ licenses:
38
+ - GPL-2.0
39
+ metadata: {}
40
+ post_install_message:
41
+ rdoc_options: []
42
+ require_paths:
43
+ - lib
44
+ required_ruby_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ requirements: []
55
+ rubygems_version: 3.1.3
56
+ signing_key:
57
+ specification_version: 4
58
+ summary: Loads and serves configs.
59
+ test_files: []