Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Building a Filterable Log Viewer With Downshift and match-sorter

DZone's Guide to

Building a Filterable Log Viewer With Downshift and match-sorter

Learn how this filterable log viewer was written in JavaScript using the Downshift library.

· Performance Zone ·
Free Resource

Maintain Application Performance with real-time monitoring and instrumentation for any application. Learn More!

This was a fun little build, but I wish I remembered to turn on my stream. It was kinda nice to just write some code, too!

<LogViewer> takes a stream of server logs, or process logs, or any flat text file (let's be honest) and turns it into a searchable, filterable little thing. Type in the input box, find what you're looking for. Matched strings are highlighted so you know what you're doing.

Image title

Source.

The whole thing fits into 69 lines of beautifully rendered code and 1071 node_modules dependencies. You can see the code on GitHub.

Try <LogViewer>

Here's How It Works

<LogViewer> is built out of two main components:

  1. <LogViewer> renders a Downshift component and munches a text file into a list of logs.
  2. <LogRow> takes care of individual lines and highlighting matched strings.

LogViewer

class LogViewer extends React.Component {
    static getDerivedStateFromProps(props, state) {
        return {
            ...state,
            logs: props.logs.split("\n")
        };
    }

    render() {
        const { logs } = this.state;

        return (
            <Downshift>
                {({ getInputProps, inputValue }) => {
                    const filtered =
                        (!inputValue && logs) || matchSorter(logs, inputValue);

                    return (
                        <div>
                            <input
                                {...getInputProps()}
                                placeholder="Filter logs ..."
                            />
                            <p>{filtered.length} matches</p>
                            <pre>
                                {filtered.map(log => (
                                    <LogRow match={inputValue}>{log}</LogRow>
                                ))}
                            </pre>
                        </div>
                    );
                }}
            </Downshift>
        );
    }
}

We're using getDerivedStateFromProps to take our logs, which is a flat string, and turn it into an array of entries. Right now, that's just splitting by newlines, but we could perform contextual parsing and understand that a single log can span multiple lines.

Perhaps the parser function should come from props...

The render method takes logs from state and returns a <Downshift> component. Downshift takes care of driving our input field and some other tidbits that are tedious to do ourselves.

Inside Downshift's render prop, we use matchSorter to filter logs based on user input. I don't know what string matching algorithm matchSorter uses, but it's really fast.

A+ library!

Finally, we render a <div> with an input field controlled by Downshift, a p with the count of matches, and a pre with all our logs in a loop. We render each log entry with <LogRow>, providing the current match and log to be rendered.

LogRow

The <LogRow> component renders a string of text, potentially highlighting a part of it.

const LogRow = ({ match, children }) => {
    const _match = match.toLowerCase();

    const chunks = match.length
        ? children.split(new RegExp("(" + match + ")", "ig"))
        : [children];

    return (
        <div>
            {chunks.map(
                chunk =>
                    chunk.toLowerCase() === _match ? (
                        <Highlight>{chunk}</Highlight>
                    ) : (
                        chunk
                    )
            )}
        </div>
    );
};

We convert the matched string to lower case. Gonna use it to decide which part of the log to highlight.

Then we split our log on a regex using the provided match.

The result is an array of log fragments like this

match = 'cat'
log = 'my cat is grumpy'

chunks --> ['my ', 'cat', ' is grumpy']

When you split on regex and wrap your split point in parenthesis, (), it's preserved in your output. Perfect for our purposes and pretty fast too.

Rendering is a matter of looping through our chunks array and returning either a flat string or the <Highlighted> styled component.

The <Highlighted> component is simplistic because I'm no designer.

const Highlight = styled.span`
    color: red;
    background: yellow;
`;

Red color, yellow background. High contrast.

Useful?

That was an MVP. Should I make it better? Should I open source it?

Anyone out there who'd use it? Ping me on Twitter.

P.S.: You should also follow me on Twitter here. It's where I go to shoot the sh*t about programming.

Collect, analyze, and visualize performance data from mobile to mainframe with AutoPilot APM. Learn More!

Topics:
performance ,tutorial ,logging ,logs ,downshift

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}