Logging in Elm

Here’s the translation of the Go logging example to Elm, formatted in Markdown suitable for Hugo:

import Html exposing (Html, div, text)
import Html.Attributes exposing (style)
import Time
import Task

-- Elm doesn't have a built-in logging package like Go's log package.
-- Instead, we'll simulate logging by creating a custom type and functions.

type alias LogEntry =
    { timestamp : Time.Posix
    , message : String
    }

type alias Model =
    { logs : List LogEntry }

type Msg
    = AddLog String
    | LogAdded Time.Posix String

init : () -> (Model, Cmd Msg)
init _ =
    ( { logs = [] }
    , Task.perform (\_ -> AddLog "standard logger") Time.now
    )

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of
        AddLog message ->
            ( model
            , Task.perform (\time -> LogAdded time message) Time.now
            )
        
        LogAdded time message ->
            ( { model | logs = LogEntry time message :: model.logs }
            , Cmd.none
            )

view : Model -> Html Msg
view model =
    div []
        (List.map (\log -> 
            div [ style "margin-bottom" "10px" ]
                [ text (formatLogEntry log) ]
         ) (List.reverse model.logs))

formatLogEntry : LogEntry -> String
formatLogEntry entry =
    let
        timestamp = 
            String.fromInt (Time.posixToMillis entry.timestamp)
    in
    timestamp ++ ": " ++ entry.message

main : Program () Model Msg
main =
    Browser.element
        { init = init
        , update = update
        , view = view
        , subscriptions = \_ -> Sub.none
        }

This Elm code provides a basic simulation of logging functionality. Here’s an explanation of the key parts:

  1. We define a LogEntry type to represent each log message with a timestamp and message content.

  2. The Model contains a list of LogEntry items.

  3. We use the Time module to get the current time for each log entry.

  4. The init function sets up the initial model and adds the first log message.

  5. The update function handles adding new log messages to the model.

  6. The view function displays all log messages, formatting them with a timestamp.

  7. We use the Browser.element program to set up the Elm application.

To run this Elm program, you would typically compile it to JavaScript and include it in an HTML file. The output would be displayed in the browser, with each log message appearing as it’s added.

Note that Elm, being a functional language for web applications, doesn’t have direct equivalents to some of Go’s logging features like writing to different outputs or structured logging. Instead, logging in Elm is typically done by updating the application state and rendering it to the view.

For more advanced logging needs in a real Elm application, you might consider using ports to interact with JavaScript logging libraries or sending log data to a server.