1%% Copyright (c) 2011-2012 Basho Technologies, Inc.  All Rights Reserved.
2%%
3%% This file is provided to you under the Apache License,
4%% Version 2.0 (the "License"); you may not use this file
5%% except in compliance with the License.  You may obtain
6%% a copy of the License at
7%%
8%%   http://www.apache.org/licenses/LICENSE-2.0
9%%
10%% Unless required by applicable law or agreed to in writing,
11%% software distributed under the License is distributed on an
12%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
13%% KIND, either express or implied.  See the License for the
14%% specific language governing permissions and limitations
15%% under the License.
16
17%% @doc Lager's top level supervisor.
18
19%% @private
20
21-module(lager_sup).
22
23-behaviour(supervisor).
24
25%% API
26-export([start_link/0]).
27
28%% Callbacks
29-export([init/1]).
30
31start_link() ->
32    supervisor:start_link({local, ?MODULE}, ?MODULE, []).
33
34init([]) ->
35    %% set up the config, is safe even during relups
36    lager_config:new(),
37    %% TODO:
38    %% Always start lager_event as the default and make sure that
39    %% other gen_event stuff can start up as needed
40    %%
41    %% Maybe a new API to handle the sink and its policy?
42    Children = [
43        {lager, {gen_event, start_link, [{local, lager_event}]},
44            permanent, 5000, worker, dynamic},
45        {lager_handler_watcher_sup, {lager_handler_watcher_sup, start_link, []},
46            permanent, 5000, supervisor, [lager_handler_watcher_sup]}],
47
48    CrashLog = decide_crash_log(lager_app:get_env(lager, crash_log, false)),
49
50    {ok, {{one_for_one, 10, 60},
51          Children ++ CrashLog
52         }}.
53
54validate_positive({ok, Val}, _Default) when is_integer(Val) andalso Val >= 0 ->
55    Val;
56validate_positive(_Val, Default) ->
57    Default.
58
59determine_rotation_date({ok, ""}) ->
60    undefined;
61determine_rotation_date({ok, Val3}) ->
62    case lager_util:parse_rotation_date_spec(Val3) of
63        {ok, Spec} -> Spec;
64        {error, _} ->
65            error_logger:error_msg("Invalid date spec for "
66                                   "crash log ~p~n", [Val3]),
67            undefined
68    end;
69determine_rotation_date(_) ->
70    undefined.
71
72decide_crash_log(undefined) ->
73    [];
74decide_crash_log(false) ->
75    [];
76decide_crash_log(File) ->
77    MaxBytes = validate_positive(application:get_env(lager, crash_log_msg_size), 65536),
78    RotationSize = validate_positive(application:get_env(lager, crash_log_size), 0),
79    RotationCount = validate_positive(application:get_env(lager, crash_log_count), 0),
80
81    RotationDate = determine_rotation_date(application:get_env(lager, crash_log_date)),
82
83
84    [{lager_crash_log, {lager_crash_log, start_link, [File, MaxBytes,
85                                                      RotationSize, RotationDate, RotationCount]},
86      permanent, 5000, worker, [lager_crash_log]}].
87